0

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?

Community
  • 1
  • 1
Junaid
  • 1,708
  • 16
  • 25
  • I see no reason why *not* to have linked entities in this case. At the very least they're useful navigation properties. As a matter of personal preference, I'd recommend starting with `User` or `Role` and navigating from there since those are the aggregate roots (depending on the context) and there would never be a situation of referencing `UserRoles` outside the context of one of those roots. – David Oct 31 '14 at 18:43
  • @David I agree with having the linked entity. However I am more concerned about the use of linked entity for navigation. Is it just a matter for preference or are there any defined best practices are this? – Junaid Oct 31 '14 at 18:46
  • Well, the best practice in this regard would likely be to navigate from the aggregate root as well simply as a matter of maintaining the logical business domain. Why are you concerned about navigating through a property? – David Oct 31 '14 at 18:48
  • @David I have added more details to question with my concerns. See if it makes sense. – Junaid Oct 31 '14 at 19:05
  • The first option in the update doesn't make a lot of sense, still thinking from a domain-driven-design point of view. If the `User` and the `Role` are the models, there logically can't be an association between two of them if those don't don't both first exist. I still see no reason not to use the navigation properties, rather than pollute the domain by treating every object as an aggregate root. – David Oct 31 '14 at 19:09

0 Answers0