Search code examples
linq-to-entities

.Where(<condition>).FirstOrDefault() vs .FirstOrDefault(<condition>)


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.


Solution

  • 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.