LINQ to SQL: Selecting a Single Row

Tonight I'm playing around with LINQ to SQL using the AdventureWorks database.  I'm going to load a product from the Product table given the ProductID, therefore loading a single product.  Simple right?  There are a couple of was to construct a LINQ statement to retrieve a record:

LINQ Query 

public Product GetProduct(int productID)
{
    AdventureWorksDBDataContext db = new AdventureWorksDBDataContext();
    Product product = (from p in db.Products
                       where p.ProductID == productID
                       select p).Single();
    return product;
}

Using a Lambda expression 

public Product GetProduct(int productID)
{
    AdventureWorksDBDataContext db = new AdventureWorksDBDataContext();
    Product product = db.Products.Single(p => p.ProductID == productID);
    return product;
}

If you notice I'm using the Single() extension method, which will absolutely do the job... when the record exists.  The gotcha is if the record doesn't exist an exception is thrown.  Instead of using the Single() method, use SingleOrDefault().  This is one you'll learn the hard way... I did.  Here's a sample using the Lambda expression without worrying about an exception when the record is missing.

Using a Lambda expression with SingleOrDefault 

public Product GetProduct(int productID)
{
    AdventureWorksDBDataContext db = new AdventureWorksDBDataContext();
    Product product = db.Products.SingleOrDefault(p => p.ProductID == productID);
    return product;
}


Bookmark and Share

Related posts

Comments are closed