In my project I need to select one row values using linq
try
{
return database.Employees.Where(x => id.Equals(x.ID)).Single();
}
catch (InvalidOperationException Ix)
{
throw;
}
using that I will get corresponding row values through entity object.But it is throwing an error if the result set is empty.The problem is in my project Exception is must to be logged.
How can I manage this code with out going to exception.
You’re using
Single()which is documented to throw an exception if there are no results. If you don’t want that behaviour, don’t use that method 🙂If you use
SingleOrDefault()it will return null if there are no results. It will still throw an exception if there are multiple results, however. Alternatively you could useFirstOrDefaultto avoid this.Note that you can specify a predicate in
Single/SingleOrDefaultas well, so you don’t need aWherecall first: