EF 4 Code First和M2M2M [英] EF 4 Code First and M2M2M
问题描述
嗨!
首先使用Entity Framework 4和代码如何创建支持此场景的模型:
Using Entity Framework 4 and code first how would I create a model that supports this scenario:
应用程序,有用户,每个用户属于一个或
更多组,每个用户可以拥有一个或
更多角色。
In an application, there are users, each user belongs to one or more groups and for each group the user can have one or more roles.
示例:
我希望能够说," ;给我Lisa",并且响应返回lisa的用户对象,包含她所属的组。对于每个组,都有一个列表属性,其中包含她对该特定组的所有角色
任何人都可以帮助我首先使用代码对此进行建模,任何帮助/代码示例,都会太棒了!
Can anyone help me model this using code first, any help/code samples, would be great!
/最好的问候Vinblad
/Best regards Vinblad
推荐答案
Hi Vinblad,
Hi Vinblad,
您需要将连接表建模为类。即拥有User,Group,Role和UserGroup类,User将拥有UserGroup的集合,UserGroup将具有对Group和Role集合的引用。
You will need to model the join table as a class. I.e. have User, Group, Role and UserGroup class, User would have a collection of UserGroup and UserGroup would have a reference to a Group and a collection of Role.
public class User
{
public int UserId { get; set; }
public string Name { get; set; }
public ICollection<UserGroup> Groups { get; set; }
}
public class UserGroup
{
public int UserGroupId { get; set; }
public Group Group { get; set; }
public ICollection<Role> Roles { get; set; }
}
public class Group
{
public int GroupId { get; set; }
public string Name { get; set; }
}
public class Role
{
public int RoleId { get; set; }
public string Name { get; set; }
}
~Rowan
这篇关于EF 4 Code First和M2M2M的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!