Skip to main content

Differences between First() and FirstOrDefault() and Single() and SingleOrDefault()

Single() returns a single item and throws an exception if there is either none or more than one item. First() returns the first item or throw when there is no item. FirstOrDefault() returns the first item or return null (in most cases) when there is no item.

When to use Single(), First(), SingleOrDefault() and FirstOrDefault()

It depends on the situation. If you are sure that you should always get a single result Single() is proper method. If you need to get null value if no other is found, you can consider SingleOrDefault() here. If there could be more than one record consider using First(), and if the first result can be null, you could use FirstOrDefault().

If you know you should always get a single record back from the db, for a given query then Single() is the 'right' one to use. In other situations the others may be more appropriate. In previous versions of EF we were limited to First() and FirstOrDefault() which work for scenarios where you are expecting a single record but they won't warn you if you actually get more than that single record back which could be important depending on the situation.

- Advertisement -