5

Using Linq to Entities is there a difference between the following?

db.EntityName.Where(a => a.Id == id).FirstOrDefault();

db.EntityName.FirstOrDefault(a => a.Id == id);

Or is it simply a matter of personal preference?

Thanks.

sakura-bloom
  • 4,524
  • 7
  • 46
  • 61

2 Answers2

7

Both generate the same SQL statement. The second approach is shorter, while the first might be clearer to some developers. Ultimately it's a matter of personal preference.

You can inspect the SQL using the ObjectQuery.ToTraceString method.

Ahmad Mageed
  • 94,561
  • 19
  • 163
  • 174
0

I've experienced differences on these two statements. I think at least older EF-versions were handling these two clauses differently especially when there are possibility to query end up resulting "null".

Not sure if this have been already fixed, but my spines still use always the first version:

db.EntityName.Where(a => a.Id == id).FirstOrDefault();

  • https://entityframework.net/knowledge-base/31162938/orderby---firstordefault--condition---vs--where--condition---orderby---firstordefault--?msclkid=d199d979b3fe11ec9affed6ae92b5c38 – illmojo Apr 04 '22 at 10:22