Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
565 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 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...