[Table("User")]
public class User
{
public int Id { get; set; }
public string Name { get; set; }
public string Surname { get; set; }
public string UserName { get; set; }
//I should join with User.UserName and UserRoles.UserName
public List<UserRoles> UserRolesList { get; set; }
}
[Table("Role")]
public class Role
{
public int Id { get; set; }
public string RoleKey { get; set; }
public string Description { get; set; }
}
[Table("UserRoles")]
public class UserRoles
{
public int Id { get; set; }
public string UserName { get; set; }
public string RoleKey { get; set; }
}
public class MyDbContext : DbContext
{
public MyDbContext(DbContextOptions<MyDbContext> options) : base(options)
{
}
public DbSet<User> Users { get; set; }
public DbSet<Role> Roles { get; set; }
public DbSet<UserRoles> UserRolesList { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
}
}
//Getting all users with roles
var usersWithRoles= _dbContext.Users.Include(b => b.UserRolesList).ToList();
我有3个表(User,Role和UserRoles),我想用UserName列连接User和UserRoles表。但是EntityFramework不允许在没有主键列的情况下执行此操作。我该怎么办?
谢谢。
答案 0 :(得分:0)
我认为您应该像下面那样设计UserRole表
[Table("UserRoles")]
public class UserRoles
{
public int Id { get; set; }
public int UserId { get; set; }
public int RoleId { get; set; }
public User User {get; set;}
public Role Role {get;set;}
}
现在,您可以使用userId加入并从用户表中获取用户名。也可以通过roleId与角色表连接并获取角色密钥。