简体   繁体   中英

Entity Framework 4: Mapping several assocation tables to entities

I am kind of new to Entity Framework and ORMs. I have a simple database schema that is kind of like this.

User:
   Id
   Name

Group:
   Id
   Name

Role:
   Id
   Name

There are many-many between groups and users. Also, there is many-many between users and roles. However, Roles are per group. So we could have the following:

User A belongs to Group 1 with Roles a,b,c and belongs to Group 2, but has Roles d,e,f.

So we have some association tables like so:

UserRoles:
   UserId -> User.Id
   RoleId -> Role.Id

UserGroups
   UserId -> User.Id
   GroupId -> Group.Id

GroupRoles:
   GroupId -> Group.Id
   RoleId -> Role.Id

So, in my entities I want to have a Role entitiy, a User entity with a collection of Roles and a Group entity with a collection of Users and a collection of Roles.

When I load a group, I want to only load the users in that group and only that users roles for that group.

So my question: In the above example. How do I make it so when I load Group 1, I want to see User A with Roles a,b,c and NOT Roles d,e,f.

Thanks, JR

You need to call something like Group.User.Roles to get all Roles the user belongs to in the Group. something like:

var group1 = objectContext.Groups.Where(x => x.GroupId == 1);
var userARoles = group1.Users.Where(x => x.UserId == "A").Roles;

Does this help you?

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM