I have the following database table structure.
User
----
userid
username
firstname
lastname
Role
----
RoleId
Name
Description
UserRole
--------
UserRoleId
UserId
RoleId
Can anyone help me how to properly design the datadomain classes to use in EF so that when i get the User i also get the rolename and roledescription?
Many Thanks
The UserRole
table does not need to have Id
, the primary key is the combination of other two foreign keys, so the model should be:
public class User
{
public int UserId { get; set; }
public string UserName{ get; set; }
public string FirstName {get; set;}
public string LastName {get; set;}
public virtual ICollection<Role> Roles { get; set; }
}
public class Role
{
public int RoleId { get; set; }
public string Name{ get; set; }
public string Description{get; set;}
public virtual ICollection<User> Users{ get; set; }
}
EF will generate the tables for two above entities and creates a new table for many-to-many relationship, which contains the two Primary keys of above entities.
but is you want the intermediate UserRole
table have Id
, then :
public class User
{
//Some properties
public virtual ICollection<UserRole> UserRoles { get; set; }
}
public class Role
{
public virtual ICollection<UserRole> UserRoles{ get; set; }
}
public class Role
{
public int UserRoleId { get; set; }
public int UserId { get; set; }
public virtual User User { get; set; }
public int RoleId { get; set; }
public virtual Role Role { get; set; }
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.