We changed a relationship from required to optional, now the resulting SQL produced by EF Core's Include() does a left outer join rather than inner join. Problem is that those optional entities have query filters on them that is required.
Let's say we have the following;
public class First
{
public int? SecondId { get; set; }
}
public class Second
{
public First First { get; set; }
public int ThirdId { get; set; }
}
public class Third
{
public Second Second { get; set; }
public string Tenant { get; set; }
}
public class MyContext : DbContext
{
protected readonly string _tenant;
...
modelBuilder.Entity<Third>(p =>
{
p.HasQueryFilter(x => Tenant == _tenant);
});
...
}
And then we do the following:
MyContext.First.Include(p => p.Second).ThenInclude(p => p.Third);
This will produce a LEFT OUTER JOIN since the relationship is optional. This will of course then bypass the query filter. Is there a way to make this Include an INNER JOIN instead?
Currently this is solved with adding some more conditions to the where later:
.Where(p => p.Second.Third.Tenant == _tenant);
But this is undesirable since in some edge cases the _tenant is null and will then give the wrong data.
I know I can flip it around and go for
MyContext.Third.Include() ...
But this is also undesirable as First in this scenario has a lot of other related data and I don't want to endlessly chain Include().ThenInclude() to the point of ad absurdum.
Can I force inner joins with optional entities? Or do I manually have to write the SQL for this?
.Where(p => p.Second.Third.Tenant == _tenant);
you can change it to.Where(p => _tenant != null ? _tenant.Contain(p.Second.Third.Tenant) : p.Second.Third.Tenant == p.Second.Third.Tenant);
can it solve your problem?