I\'ve searched around and haven\'t really found a clear answer as to when you\'d want to use .First
and when you\'d want to use .FirstOrDefault
wit
Another difference to note is that if you're debugging an application in a Production environment you might not have access to line numbers, so identifying which particular .First()
statement in a method threw the exception may be difficult.
The exception message will also not include any Lambda expressions you might have used which would make any problem even are harder to debug.
That's why I always use FirstOrDefault()
even though I know a null entry would constitute an exceptional situation.
var customer = context.Customers.FirstOrDefault(i => i.Id == customerId);
if (customer == null)
{
throw new Exception(string.Format("Can't find customer {0}.", customerId));
}