Relationship 1: N with EF

1

I have a table of units as below:

public class Unity
{
 public int Id {get;set }
 public string Name{ get; set; }
}

public class UsersRight
{
 public int Id {get;set }        
 public string Name{ get; set; }
 public int Value{ get; set; }
}

Each user can have access to 1 or n units. I'll have a list with the unit logs.

var userRight = new List<UsersRight>;
userRight = _DAL.UserRights(user);

var listUser = new List<Unity>; 

foreach (var item in userRight)
{ 
  listUser.add( new Unity(Name = item.Name, Id = item.Value));
}

What is the most efficient way to do this with EF? I am using ASP.NET Identity.

    
asked by anonymous 24.03.2017 / 16:36

1 answer

2

In your case with a Unidade can have several Usuarios and a Usuario because it has several Unidade , it characterizes an N: N relationship, which in this case would have to be done with an extra table doing the relationship between the two.

Example:

  

Unit table

    public class Unity
{
 public int UnityId {get;set }
 public string Name{ get; set; }
}
  

User table

    public class UsersRight
{
 public int UsersRightId {get;set }        
 public string Name{ get; set; }
 public int Value{ get; set; }
}
  

This is the connection table between the two tables:

    public class UserUnitty
{
     public int UsersRightId {get;set }
     public int UnityId{ get; set; }

     public virtual UsersRight UsersRight{get;set;}
     public virtual Unity Unity{get;set;}

}

Considerations:

  • In the UserUnity table, virtual is used, virtual modifier is used by EF to do Lazy Loading, which needs to create proxy instances that will be overridden in these virtual properties. In case when you query these classes will not be filled.
  • I have used UnityId and UserRightId to not use DataAnnotations , but if you want to keep as orignal you can just use DataAnnotations to specify which table belongs that ForeingKey .
24.03.2017 / 19:27