I have a many to many relationship between two entities. For simpicity, my entities are
class User
{
int Id;
string Name;
}
class Roles
{
int Id;
string Name;
}
I have created linked entity with one additional property to link these as below
class UserRole
{
int Id;
User user;
Role role;
DateTime created;
}
I know one way is to create a List
of UserRole
in User
and Role
entities to achieve a many to many relation. This is very well define on another post.
Here, to get the list of users in a role, you would probably write something like
User.UserRole.Where(r=>r.Role.Id = 1);
However I found out that another way is not define this relation between User
and Role
, i.e. don't have the List
of UserRole
in both entities. To access the related data, you would use the UserRole
entity.
So to get the list here, you need to do
UserRole.Include(u=>u.User).Include(r=>r.Role).Where(a=>a.Role.Id = 1)
EDIT:
I like the first way however I am concerned that there are multiple ways to create associations.
1) You can create a UserRole
with only User
property set. Then create a new Role
and add the newly created UserRole
to the List<UserRole>
for the Role
2) The other way is to create User
and Role
(without setting List<UserRole>
for Role
). Then you create a UserRole
and set both User
and Role
I am not sure right way? Should linked entity be navigated for retrieving data?