[英]Entityframework query many to many
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? 谁能帮助我如何正确设计要在EF中使用的datadomain类,以便在我获得用户时也获得角色名和角色描述?
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: UserRole
表不需要具有Id
,主键是其他两个外键的组合,因此模型应为:
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. EF将为上述两个实体生成表,并为多对多关系创建一个新表,其中包含上述实体的两个主键。
but is you want the intermediate UserRole
table have Id
, then : 但是您是否希望中间
UserRole
表具有Id
,则:
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; }
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.