EF6 generates WHERE clause in unexpected order

53 views Asked by At

I'm using the solution from this answer to form an Expression<Func<Proposal, bool>> object (where Proposal is an entity type in my app), according to the searching criteria input on a WebForm page by users. The string representation of the resulting object I see during debugging is like this:

{Param_0 => (
  (
    (
      (Param_0.SubmitDate >= value(Proposals+<>c__DisplayClass4_0).submitDateBegin)
      AndAlso (Param_0.SubmitDate <= value(Proposals+<>c__DisplayClass4_0).submitDateEnd)
    ) AndAlso (Param_0.ProposingOrgNode.ID == value(Proposals+<>c__DisplayClass4_0).proposingOrgNode.ID)
  ) AndAlso value(Proposals+<>c__DisplayClass4_0).undertakerRelations.Contains(Param_0.UndertakerRelation)
)}

(I assume Proposals+<>c__DisplayClass4_0 means some compiler magic played on my "Proposals.aspx" page object.)

I pass this object into myDbContextObj.Proposals.Where(), expecting the order of the expressions in the SQL WHERE clause which EF6 generates would match that of the above. However the generated WHERE clause is like this:

WHERE ([Extent1].[UndertakerRelation] IN (N'A', N'B', N'C'))
  AND ([Extent1].[SubmitDate] >= @p__linq__0)
  AND ([Extent1].[SubmitDate] <= @p__linq__1)
  AND (([Extent1].[ProposingOrgNodeID] = @p__linq__2) OR (([Extent1].[ProposingOrgNodeID] IS NULL) AND (@p__linq__2 IS NULL)))

The "UndertakerRelation" condition jumps ahead as the first one of the whole clause.

Why is this happening? How can I stop this behavior, ensuring that EF6 generates the expressions in supposed order?

.NET Framework version: 4.8
EF version: 6.4.4 (Not EF Core)
SQL Sever version: 2019 LocalDB

(The reason I care about this issue: I've heard that the order of the expressions in WHERE clause affects if indexes are used or not, and hence the selectivity and performance.)

0

There are 0 answers