I'm using Entity Framework 6 and I have few entities and a query like the following:
var results = (from e1 in dataContext.Entity1
.Where(x => x.Key1 == 1)
from e2 in dataContext.Entity2
.Where(x => x.Key2 == e1.Key1)
.DefaultIfEmpty()
from e3 in dataContext.Entity3
.Where(x => x.Key3 == e1.Key1 || x.Key3 == e2.Key2)
.DefaultIfEmpty()
select new
{
E1 = e1,
E2 = e2,
E3 = e3
}).ToList();
Since the joins to Entity2 and Entity3 are left joins, e2 or e3 may be null. I found out if e2 is null, exception System.Reflection.TargetException is thrown with message "Non-static method requires a target". And if I change the join to Entity3 as the following, I still got the same error.
from e3 in dataContext.Entity3
.Where(x => x.Key3 == e1.Key1
|| (e2 != null && x.Key3 == e2.Key2))
.DefaultIfEmpty()
How can I change the query?