Handling 'Sequence has no elements' Exception

You are using linq's First() method, which as per the documentation throws an InvalidOperationException if you are calling it on an empty collection.

If you expect the result of your query to be empty sometimes, you likely want to use FirstOrDefault(), which will return null if the collection is empty, instead of throwing an exception.


First() is causing this if your select returns 0 rows. You either have to catch that exception, or use FirstOrDefault() which will return null in case of no elements.


Instead of .First() change it to .FirstOrDefault()