views:

649

answers:

1

Any ideas why LINQ to Entities doesn't support SingleOrDefault() but instead ask to use FirstOrDefault()?

Will SingleOrDefault() functionality be replaced? By what?

+1  A: 

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();

Source: MSDN

KClough
I didn't see the code you provided in that link. The implementation you've shown appears to be exactly like FirstOrDefault() - at least from my memory. SingleOrDefault() would return null if there are no results, return a single result if only one exists, or throw an exception if there is more than one result.
Ryan Versaw
Actually, SingleOrDefault throws when there is more than one result found. That's the point of it--zero or one record must be returned; otherwise an error has occurred. From the docs: "this method throws an exception if there is more than one element in the sequence." Your version isn't correct.
Will
Updated my implementation, thanks for the comments.
KClough