Any ideas why LINQ to Entities doesn't support SingleOrDefault()
but instead ask to use FirstOrDefault()
?
Will SingleOrDefault()
functionality be replaced? By what?
Any ideas why LINQ to Entities doesn't support SingleOrDefault()
but instead ask to use FirstOrDefault()
?
Will SingleOrDefault()
functionality be replaced? By what?
I'm not sure why it was left out, but you can always roll your own.
I found a similar response to this question on MSDN, here is an implementation based off of that code.
public static TElement SingleOrDefault<TElement>
(this IQueryable<TElement> query)
{
if (query.Count() == 1)
return query.First();
else if (query.Count() == 0)
return null;
else
throw new InvalidOperationException();
}
// Use it like this
Product prod = (from p in db.Product
where p.ProductID == 711
select p).SingleOrDefault();