this might be an old and on-going question for Entity Framework Core but I researched a lot and couldn't get an answer. We used to write store procedure in SQL so we will use operator like Inner Join and Left Join, recently we're rewriting everything in Entity Framework Core using C#. However, we found that no matter if we use linq-to-sql or Include operator, the sql execution behind the scene is always using the LEFT JOIN.
For example our store procedure will look like
SELECT *
FROM Users u
INNER JOIN UserRole ur on ur.Uid = u.Uid
LEFT JOIN UserGroup ug on ug.Uid = u.Uid
Suppose we already have a User, UserRole and UserGroup class defined in Entity Framework already, how could we to perform Inner Join with UserRole and Left Join with UserGroup at same time in Entity Framework Core here?
Things I've tried with using Include
:
dbContext.Users.Inlcude(u => u.UserRoles).Include(u => u.UserGroups).ToList();
and using linq-to-sql
:
from u in dbContext.Users
join ur in dbContext.UserRole on u.Uid equals ur.Uid
join ug in dbContext.UserGroup on ug.Uid = u.Uid
select new {u.Name, ur.UseRole, ug.Groupname}
Both above two approach is using a LEFT JOIN
So far what we can do is using DbQuery with FromSql by plain sql, but we don't think that's a property way of using Entity Framework. So can it be done with traditional Include and linq-to-sql ways?
Also I looked at answer about using WithRequired
and WithOptional
in table mapping relationship with FluentApi, but that's not what I want, because some of my business logic needs INNER JOIN
between User
and UserRole
while other scenario may need LEFT JOIN
between User
and UserRole
, so we need to write query or code that EF understand to differentiate the correct join we want.