这里举一个例子,用到了三个实体类,分别是
[Table("t_user")]
public class User
{
[Key]
public long Id {
get; set; }
public string UserName {
get; set; }
public string Password {
get; set; }
public string Email {
get; set; }
public List<Role> Roles {
get; set; }
}
用户类
[Table("t_role")]
public class Role
{
[Key]
public long Id {
get; set; }
public string Name {
get; set; }
public List<User> Users {
get; set; }
public List<Authority> Authoritys {
get; set; }
}
角色类
[Table("t_user_role")]
public class UserRole
{
public long UserId {
get; set; }
public long RoleId {
get; set; }
}
以及用户和角色的关系表类,这表明用户和角色是多对多的关联关系。
如果要根据用户名查询用户信息以及关联的角色信息,如何实现?这里介绍一下,我见过的3种方法。
1、第一种就是配置用户和角色间的关联关系,在数据库上下文类中加入这么一行代码
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<User>().HasMany(user => user.Roles).WithMany(role => role.Users