The usage of this extension methods depends on the situation. But I’m going to list the main differences:
– you clearly sure, that the query can return any amount of results, but you state, that you only want the first one
– you clearly sure, that the query should result in at most a single result
If result set returns many records:
- SingleOrDefault() – throws an exception
- FirstOrDefault() – returns the first record
Look at this table to view info in more memorable way
|0 VALUES||1 VALUE||MORE THAN 1 VALUE|
To sum up,
- FirstOrDefault() Returns any number of results, but I only care about the first one, there may also be no results.
- SingleOrDefault() There are 1 or 0 results, if there are more that means there’s an error somewhere.
- First() There is at least one result, and I want it ,an exception if no result returned.
- Single() There is exactly 1 result, no more, no less, and I want that on, an exception if no result returned.