0

I have the following table relations

User
  -List<Role>   on User.RoleId = Id
    -RoleDetail on Role.RoleDetailId = Id
    -Practice   on Role.PracticeId = Id

While I do have all these entities linked up in EF, I'm only able to access Roles when I query User with dbConext Include, RoleDetail & Practice are not accessible, which is understandable. Is there any way I can change how I query User to include those information?

If not, how should I join these tables efficiently? I'm not looking to foreach loop on every single user's multiple roles but a single query request. Any help/hint is appreciated.

Querying User with Role

users = _dbcontext.Users.Include(u => u.Roles)

Joining

var userQuery = _userRepository.GetUser(searchTerm);
var roleQuery = _roleRepository.GetRole();
var test = from user in userQuery join role in roleQuery on user.Roles....
2
  • Please post what have you tried with EF to get data? user and role have one-to-one relation? Commented Apr 26, 2022 at 7:05
  • 1
    yes Role has a one-to-one relation with RoleDetail & Practice. I'll post what I have so far Commented Apr 26, 2022 at 7:08

1 Answer 1

1

You need to use two Include on roles for getting all data like this:

users = _dbcontext.Users.Include(u => u.Roles).ThenInclude(x=>x.RoleDetail)
                        .Include(u => u.Roles).ThenInclude(x=>x.Practice)
                        .AsSplitQuery(); //highly recommend if you are using .Net >=5
Sign up to request clarification or add additional context in comments.

2 Comments

I had no idea about ThenInclude lol. Thanks for the reply I'll try it out
That fixed my issue, thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.