Best way to catch "Sequence contains no elements"

entity-framework entity-framework-6

Question

If Single doesn't find the element you're expecting to exist then it throws an InvalidOperationException. Only trouble is that other things result in this exception too. For example an EF Code First model being out of date.

I've tried to narrow it down by checking the exception message. However this could change and I'd be none the wiser. Is there a better way of catching this problem?

   try
    {
        return DbSet.Single(filter);
    }
    catch (InvalidOperationException exc)
    {
        if (exc.Message == "Sequence contains no elements")
        {
            throw new UserNotFoundException();
        }

        throw;
    }
1
2
4/16/2015 3:06:13 PM

Accepted Answer

Use .FirstOrDefault() instead. Then check to see if the result is null. If it is, the user wasn't found.

4
4/16/2015 3:08:19 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow