Search code examples
entity-frameworkef-code-firstexistsany

Linq To Entities - Any VS First VS Exists


I am using Entity Framework and I need to check if a product with name = "xyz" exists ...

I think I can use Any(), Exists() or First().

Which one is the best option for this kind of situation? Which one has the best performance?

Thank You,

Miguel


Solution

  • Any translates into "Exists" at the database level. First translates into Select Top 1 ... Between these, Exists will out perform First because the actual object doesn't need to be fetched, only a Boolean result value.

    At least you didn't ask about .Where(x => x.Count() > 0) which requires the entire match set to be evaluated and iterated over before you can determine that you have one record. Any short-circuits the request and can be significantly faster.