Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I query only a single item from a database using LINQ?

Tags:

linq

I would like to get a LINQ-to-SQL query that returns only one item, not a collection of them?

For example, I have a list of products with a particular name. There are no products with duplicate names in the database, so I want to be able to query and return just that instance of that product.

Products product = from p in _productContext.Products 
                   where p.name.Equals("BrownShoes") 
                   select p;

How do I do something like that?

like image 887
Mithrax Avatar asked Apr 08 '09 08:04

Mithrax


1 Answers

Use Single:

Product product = _productContext.Products
                                 .Single(p => p.Name == "BrownShoes");

or

Product product = _productContext.Products
                                 .Where(p => p.Name == "BrownShoes")
                                 .Single();

There's no query expression syntax for Single, so you have to call it as a normal extension method. At that point your query is simpler written entirely with dot notation, hence the form above. You could write it as:

Product product = (from p in _productContext.Products 
                   where p => p.Name == "BrownShoes"
                   select p).Single();

But that's got a lot more fluff. If there isn't exactly a single element in the result, an exception will be thrown.

like image 153
Jon Skeet Avatar answered Oct 11 '22 14:10

Jon Skeet