Saturday 9 July 2011

LINQ to SQL: using First vs FirstOrDefault

In the Fisharoo examples of ASP.Net 3.5 Social Networking, there is an AccountRepository class which will retrieves populated Account entites from the database using LINQ to SQL.

Here is a snippet of the code:

        public Account GetAccountByID(int AccountID)
        {
            Account account = null;

            using (FisharooDataContext dc = conn.GetContext())
            {
                account = (from a in dc.Accounts
                           where a.AccountID == AccountID
                           select a).First();
            }
            return account;
        }

See any problems with this code?

I didn't...but after running it the during development when my Account table had no records...ie i was running the Application and Registering the very first user ever...the above code threw this exception on the LINQ code:

System.InvalidOperationException: Sequence contains no elements

This is happening because the LINQ query is returning an empty set and then you're trying to call .First() on it.

I don't understand why this was written this way...especially for the GetByID method...it seems quite likely to me that there would be instances where this code could be called with an ID of an account that doesn't exist.

Either way, its easy fixed by using the FirstOrDefault() method instead...this will simply assign 'null' to the 'account' variable in the event that the LINQ query returns an empty set - lovely!

No comments:

Post a Comment