0
votes

I have the following database tables:

Table1: User
UserId
Username

Table2: Role
RoleId
Rolename

Table3: UserRole
UserId
RoleId

A User can have many Roles and a Role can have many Users. When I model this with EF, I get a User entity with a list of UserRole entities. What I want is a User with a list of Role entities.

Is there a way to model this or query via LINQ to return a User entity and the Role entities they belong to?

Thanks
Dirk

1

1 Answers

0
votes

If you model a many-to-many relation, the table in the middle will not appear in your conceptual model. (i.e. you will not have a class "UserRole" derived from "EntityObject")

If you use the EF wizard, ensure that your table "UserRole" only have these two Fields and no others. Also ensure, that you have created the foreign key constraints on both of the fields. if you have, then the wizard will create a proper many-to-many relation.

The query then probably looks something like

using(MyObjectContext context = new MyObjectContext(someParameters)){
    var theUser = (from user in context.UserSet
                  where user.UserId = XY
                  select user).First();
    theUser.Roles.Load();
}