HomeCSharp.First() throws Error in LINQ or Entity Framework Queries

.First() throws Error in LINQ or Entity Framework Queries

I use .First() method in some of the Entity Framework LINQ queries to return only one record . This works perfectly similar to the select Top 1 statemnent in SQL.

Eg :

var data = (from m in Employees
where m.Name == "Senthil"
select m).First()

But , there is an issue with this . Assume your LINQ Query does not contain any Records or the SQL Statement ( TOP 1 ) does not return any records . What would happen ??

I initially thought that it might return NULL or Nothing , but it doesn’t .

When there is no record in the query result and the .First() is used , it throws an error stating “Invalid Operation Exception : sequence contains no elements” . Not an Impressive solution . 🙁

Here comes another method that handy in this case ,Its called FirstOrDefault() which returns NULL if there is no records in the result . The FirstOrDefault() will return the default value for the requested type .

var data = (from m in Employees
where m.Name == "Senthil"
select m).FirstOrDefault();

So beware when using .First() or .Last()  , since you can use .FirstOrDefault() or .LastOrDefault() instead .

Also check what is Supported and what is not Supported in Entity Framework when using First or Last funtion in one my earlier posts .

    2 Comments

  1. Holli Tobey
    December 1, 2010
    Reply

    Amazing job. I am going to want a decent amount of time to toy with your content..

  2. Ed Eaglehouse
    October 5, 2016
    Reply

    It is not completely accurate to say that FirstOrDefault() “returns NULL if there is no records in the result”. It actually returns the _default_ value of the resultset if there are no records in the result. If the resultset selected an integer field (value type), rather than the whole entity (reference type), the returned value would be 0.

Leave a Reply

You May Also Like

This C# program calculates and displays an upper triangular matrix based on user input. Problem Statement: The program takes the...
This C# program serves as a demonstration of bitwise operators, which are fundamental operators used for manipulating individual bits in...
This C# program is designed to interchange or swap the columns of a matrix. A matrix is a two-dimensional array...