Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework .Where method chaining

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?

like image 910
e36M3 Avatar asked Nov 04 '10 15:11

e36M3


2 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); 
like image 67
Justin Niessner Avatar answered Oct 02 '22 06:10

Justin Niessner


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.

like image 24
dotariel Avatar answered Oct 02 '22 06:10

dotariel