定义深层关系/嵌套模型的模型

时间:2013-06-03 21:15:31

标签: c# entity-framework ef-code-first

我有一个看起来像这样的数据库:

tblUsers
   - UserId
tblRoles
   - RoleId

tblUserRoles
   - UserRoleId
   - RoleId
   - UserId

class User
{
   [Key]
   public virtual int UserId{ get; set; }

   [ForeignKey("UserId")] // how does this tell ef not to map it to the primary key. 
                             It needs to map to UserId which is not defined as a key.??

   public DbSet<UserRole> Roles{ get; set; }
}    

class UserRoles
{
   [Key]
   public virtual int UserRoleId{ get; set; }

   public virtual int UserId{ get; set; }
   public virtual int RoleId{ get; set; }

   [ForeignKey("RoleId")]
   Public Role RoleInfo {get; set;}
}

class Role 
{
   [Key] 
   public virtual int RoleId {get; set;}

   public string RoleName {get; set;}
}

我不认为这是正确的。我需要设置模型,其中外键不是主键,而是表中的列。我的问题:如何在没有主键的情况下定义模型并链接实体之间的关系?

2 个答案:

答案 0 :(得分:3)

您不需要声明类UserRoles,EF代码首先会创建场景背后所需的关系和表格,这就是您所需要的:

public class User
{
    public int Id {get;set;}
    public virtual ICollection<Role> Roles {get;set;}
}

public class Role
{
    public int Id {get;set;}
    public virtual ICollection<User> Users {get;set;}
}

然后覆盖您的OnModelCreating

protected override void OnModelCreating(DbModelBuilder builder)
{
    builder.Entity<User>()
    .HasMany(u => u.Roles).WithMany(r => r.Users)
    .Map(t => t.MapLeftKey("UserId")
    .MapRightKey("RoleId")
    .ToTable("UserRoles"));
}

您需要自己声明连接表的唯一时间是,如果您需要带有有效负载的many-to-many。查看此帖子many-to-many with payload

答案 1 :(得分:2)

您的意思是如何将这些表链接在一起?我通常将模型设置镜像(大多数情况下)数据库的表结构。以下是我如何设置模型。 User有一个UserRoles集合,每个集合都有Role个记录。

internal class User
{
    public User()
    {
        UserRoles = new List<UserRole>();
    }

    [Key]
    public int UserId { get; set; }

    public ICollection<UserRole> UserRoles { get; set; }
}

internal class UserRole
{
    [Key]
    public int UserRoleId { get; set; }

    public int UserId { get; set; }
    public int RoleId { get; set; }

    [ForeignKey("UserId")]
    public User User { get; set; }

    [ForeignKey("RoleId")]
    public Role Role { get; set; }
}

internal class Role
{
    public Role()
    {
        UserRoles = new List<UserRole>();
    }

    [Key]
    public int RoleId { get; set; }

    public string RoleName { get; set; }

    public ICollection<UserRole> UserRoles { get; set; }
}

所以基本上用户和UserRole之间有一对多,RoleUserRole之间有一对多