I’m trying to understand some fundamental best practices using Entity Framework.
My EDM design has Group and User entities which the Group may contain users and other groups.
The question is:
What is the best way to retrieve the users from a group?
For getting the groups its easy, just creating the context object and creating a list from the groups table.
But when I want the see the users within a group, the context is closed (as it should be).
I thought about two approaches:
1) sending the group back, attaching it to context and use the Load() method on the Users and return the List of Users.
Here I don’t know when to attach and when I shouldn’t and when the EDM will grow I will have to do a lot back and forth for each reference to load
2) linq query from the user side.
from u in context.Users where u.Groups.Contains(group) select u
Here I’m getting an exception that only primitive types can be used.
So what is the the right way to do so?
Thanks
Ronny
It’s not quite clear whether you have a 1-to-many or many-to-many relationship between your users and groups. According to the description up top,
a group may contain users– it’s one to many. According to your code:from u in context.Users where u.Groups.Contains(group) select u– it’s many-to-many. Thus I’ll provide samples for both cases.One to many – a Group contains multiple Users, a User can belong to only one Group:
Many to many – a Group contains multiple Users, a User can belong to multiple Groups: