So….. I have used the .First() method in many of my LINQ queries to make sure that my query only returns one record. I thought this would be a great way to insure isolation of one record. Very similar to a TOP 1 statement in SQL. However, there is an issue with this concept. If your TOP 1 SQL statement doesn’t find any records it returns nothing. I guess I sort of hoped that the .First() method would do something similar – say return NULL or something like that. It doesn’t! Instead it throws an error stating “InvalidOperationException : sequence contains no elements”. Not what I had hoped for.
No worries though! There apparently was a reason for this method to find 1 or flip out as the LINQ team also provides the FirstOrDefault() method which will return NULL if no records were found. Their documentation on the101 LINQ Samples page doesn’t state anything about throwing an error. It doesn’t really state anything at all about what would happen if the First() item wasn’t found. It does state however that the FirstOrDefault() method will return the default value for the requested type – IE NULL!
You can face above errors on using .First(), .Last(), or .Single() method to make sure the query returns only single record. You can use .FirstOrDefault(), .LastOrDefault(), or .SingleOrDefault() instead.
Happy Programming!!
Comments
Post a Comment