Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 393
SamSamet Avatar asked Sep 06 '13 01:09

SamSamet


1 Answers

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.

like image 183
Mohsen Alikhani Avatar answered Nov 20 '22 16:11

Mohsen Alikhani