I’m just getting started with LINQ and I’m trying to select and return a product price from database, like so:
public int GetPricePerKg(Product prod)
{
var result = from p in dc.Products
where p.pk_product_id == prod.pk_product_id
select p.product_price_kg;
return result;
}
This gives me the error:
Cannot implicitly convert type ‘
System.Linq.IQueryable<int?>‘ to ‘int‘
What’s the best way to handle this? I need the price (which is an int in this case) and do some calculations with it in another place
Well, you’ve selected a query – that could in theory match 0, 1 or more records. What do you want to do in each situation? Also, it looks like
product_price_kgisint?– what do you want to do if it’s null?You might want:
… but that will throw an exception if either there isn’t exactly one matching product or the price property is null.
You can still use a query expression if you want – but I tend not to for simple cases where you then want to add a method call at the end. The query expression equivalent is:
Alternatively, you can use the version of
Single()which takes a predicate, like this:There are no doubt other variations – they’ll all do the same thing – pick whichever one you find most readable.
EDIT: Other options instead of
Singleare:First(cope with 1 or more)FirstOrDefault(cope with 0, 1 or more)SingleOrDefault(cope with 0 or 1)For the
OrDefaultversions you’d need to work out what to do if you didn’t match any products.