We have a repository (Entity Framework) which queries for single records – only a single record should exist for any given query. Initially, our queries were SingleOrDefault().
Clearly, multiple results in the query will throw exception; and none are wrapped by try/catch. Rather than wrapping these queries in a try/catch block, I proposed an extension method as follows:
public static bool IsEmpty<T>(this IQueryable<T> Query, out int Count) {
Count = Query.Count();
return Count == 0;
}
This has advantages in more ways than simply determining if I have an empty query return or single result return.
The alternative is to wrap my query in a try/catch. My question is whether the extension method or expense of catching an exception is preferred. So as not be subjective, I am specifically referring to the cost of catching and throwing an exception versus the cost of the Count() method.
Although the database is expected to only return a single record, my approach is that the database will contain unexpected records. I don’t perceive this to be an exceptional event, therefore I do not perceive the need for throwing an exception.
The typical implementation of the extension method is as follows:
var query = Repository.All().Where(*/ some criteria */);
int count;
if (query.IsEmpty(out count)) {
// handle empty return
} else if (count > 1) {
// handle unexpected returns
}
return query.Single();
Edit
An important note: we want to be informed of ambiguous results and how many records are returned.
Be careful not to execute the query multiple times by accident.
Query the
TOP 2rows to handle all cases.