Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
518 views
in Technique[技术] by (71.8m points)

c# - Many to Many Mapping Using Data Annotations

[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; }

}

I map these tables using EntityTypeConfiguration and it triggers OnModelCreate

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

I wonder If there Is a way to map them in the class Role or UserMaster. We can use

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

Could we do the mapping thing also?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you want to customize entity framework code first for many to many relationship using data annotation, you must add junction class as the following :

[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; }
}

and then related classes must be changed to :

[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; }
}

and also see this.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...