entity framework - retrieving a single entity

LINQ to entities has a pair of methods, First and FirstOrDefault. These methods return the first item in the result set. When we know that only one item is present in the result set, we can use either Single or SingleOrDefault methods.

The below code demonstrates how to construct a query using the Single method.

using (var context = new SalesOrderManagementEntities())
	IQueryable Customers = from cust in context.Customer
							where cust.CustomerId==1
							select cust;
	Customer customer = Customers.Single();

In the above code, we have first defined the query and then called the Single() method. So, the query is executed first and then customer entity is returned.

Note that if the result set does not contain any items, the Single and First methods will throw an exception. The FirstOrDefault and SingleOrDefault will not throw an exception but return default value usually null in c# and Nothing in vb.

If the result set contains more than one value and if you are using SingleOrDefault or Single, an exception will be thrown. Here, we should use First or FirstOrDefault.