Fighting with EF6/linq to SQL to get a desired result. I'd rather not have to create a view in the database.
Any ideas on why EF is converting it this way or how to trick it otherwise?
My linq predicate:
.Where(x =>
(x.AccountId == viewModel.AccountId || x.AccountId == null)
&& (x.CompanyId == viewModel.CompanyId || x.Company == null)
&& (x.FacilityId == viewModel.FacilityId || x.FacilityId == null)
)
The generated SQL:
WHERE
(([Extent1].[AccountId] = 1)
OR (([Extent1].[AccountId] IS NULL) AND (1 IS NULL))
OR ([Extent1].[AccountId] IS NULL)
)
AND
(
([Extent1].[CompanyId] = 11)
OR (([Extent1].[CompanyId] IS NULL) AND (11 IS NULL))
OR ([Extent2].[Id] IS NULL)
)
AND
(
([Extent1].[FacilityId] = 1)
OR (([Extent1].[FacilityId] IS NULL) AND (1 IS NULL))
OR ([Extent1].[FacilityId] IS NULL)
)
AND
(
([Extent1].[FacilityId] = 1)
OR (([Extent1].[FacilityId] IS NULL) AND (1 IS NULL))
)
The SQL I thought I'd get, and does achieve the desired result:
WHERE
(
([Extent1].[AccountId] = 1)
OR ([Extent1].[AccountId] IS NULL)
)
AND
(
([Extent1].[CompanyId] = 11)
OR ([Extent2].[Id] IS NULL)
)
AND
(
([Extent1].[FacilityId] = 1)
OR ([Extent1].[FacilityId] IS NULL)
)
x.AccountIdandviewModel.AccountId? are they nullable types? also, are those numbers constants (1, 11, etc.) being generated by EF?[Extent1].[AccountId] = @p__linq__0. I do see one issue|| x.Company == nullshould be|| x.CompanyId == null, but I don't think that will totally clear it up.