Home » c# » Entity Framework .Where method chaining

Entity Framework .Where method chaining

Posted by: admin February 22, 2018 Leave a comment

Questions:

Is there any difference between these two ways of querying the context?

Firm firm = base.context.Firms
            .Where(f => f.SomeId == someId)
            .Where(f => f.AnotherId == anotherId)
            .FirstOrDefault();

Firm firm = base.context.Firms
            .Where(f => f.SomeId == someId && f.AnotherId == anotherId)
            .FirstOrDefault();

It seems that chaining is perfectly fine to accomplish the AND condition. I don’t believe you can chain OR statements. Is there a reason to prefer one over another, or scenarios when one is better/more efficient?

Answers:

They should both produce the same end result (if I’m not mistaken) but I find the the second is more readable and better shows the original intent.


Update

I just verified the above statement using LINQPad. Both queries will, in fact, product the same SQL.

For example:

context.SomeTable.Where(c => c.ParentId == null)
                 .Where(c => c.Name.Contains("F"))
                 .Select(c => c.Name);

Produces:

SELECT [t0].[Name] 
FROM [SomeTable] AS [t0]
WHERE ([t0].[Name] LIKE @p0) AND ([t0].[ParentId] IS NULL)

Which is the same SQL that is produced by:

context.SomeTable.Where(c => c.ParentId == null && c.Name.Contains("F"))
                 .Select(c => c.Name);


You could also compact things a little more (which I find preferable for the same reasons as above):

var firm = base.context.Firms.FirstOrDefault(f => f.SomeId == someId 
                                                  && f.AnotherId == anotherId);

Questions:
Answers:

My guess is that as long as you are working with in IQueryable (as your context collections probably are), using the chained extensions vs the full predicate clause achieves the same thing. This is because IQueryable allows for deferred execution so essentially the same SQL is being generated behind the scenes.

Questions:
Answers:

You can debug through the code and see the SQL that gets generated as a result of each. I would imagine it turns into the same query.