views:

116

answers:

1

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

A: 

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();
}
Chrigl
For some reason (duh!) I put audit columns in the UserRole table, so of course it modelled the many-to-many relationship incorrectly. After I removed the audit columns, it mapped correctly. Thanks for the answer.
Dirk
You may also use many-2-many relations on tables with more then only the fk fields (if those other fields are not needed in your application). But to do so, you have to dig deep into the xml code of the edmx file.
Chrigl

related questions