THe linq statement below return an exception error when no match record found. Is there anyway to handle this?, Please advise, thank you
AdventureEntities hem = new AdventureEntities ();
Guid productId;
Adventure.Product list= hem.Product .Where(x => x.Product== productId).FirstOrDefault();
No, that shouldn't throw an exception. It will, however, set list
to null
- because that's what FirstOrDefault
does when there are no results.
If you then dereference list
, you'll get a NullReferenceException
. You can avoid this by just checking for nullity first:
if (list != null)
{
// Use the list
}
Also note that you can use the overload of FirstOrDefault
which accepts a predicate, to make the code simpler:
var list = hem.Product.FirstOrDefault(x => x.Product== productId);
See more on this question at Stackoverflow