8
[Table("UserMaster")]
public class UserMaster  
{
    public UserMaster()
    {
        this.Roles = new List<Role>();
    }

    [Key]    
    public int UserId { get; set; }
    public string UserName { get; set; }
    public ICollection<Role> Roles { get; set; }
 } 



[Table("Role")]
public class Role 
{
    public Role()
    {
        this.Users = new List<UserMaster>();
    }
    public int RoleId{ get; set; }
    public string Name{ get; set; }
    public ICollection<UserMaster> Users { get; set; }

}

我使用 EntityTypeConfiguration 映射这些表并触发 OnModelCreate

this.HasMany(a => a.Roles).WithMany(b => b.Users).Map(m =>
        {
            m.MapLeftKey("UserId");
            m.MapRightKey("RoleId");
            m.ToTable("UsersInRoles");
        });

我想知道是否有办法将它们映射到 Role 或 UserMaster 类中。我们可以用

[ForeignKey()]
[Key]
[Table()]

我们也可以做映射吗?

4

1 回答 1

16

如果您想首先使用数据注释为多对多关系自定义实体框架代码,则必须添加联结类,如下所示:

[Table("UsersInRoles")]
public class UsersInRoles
{
    [Key]
    [Column(Order = 1)]
    [ForeignKey("UserMaster")]
    public int UserId { get; set; }

    [Key]
    [Column(Order = 2)]
    [ForeignKey("Role")]
    public int RoleId { get; set; }

    public UserMaster UserMaster { get; set; }
    public Role Role { get; set; }
}

然后必须将相关类更改为:

[Table("UserMaster")]
public class UserMaster  
{
    public UserMaster()
    {
        this.Roles = new List<Role>();
    }

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

    public ICollection<UsersInRoles> UsersInRoles { get; set; }
 } 



[Table("Role")]
public class Role 
{
    public Role()
    {
        this.Users = new List<UserMaster>();
    }
    public int RoleId{ get; set; }
    public string Name{ get; set; }

    public ICollection<UsersInRoles> UsersInRoles { get; set; }
}

也看到了这个

于 2013-09-21T07:12:44.303 回答