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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With