frc frc - 9 months ago 65
C# Question

Get a decimal from a table

I am making a shopping cart, upon clicking

Add to cart
the user is redirected to a page that accepts the
of the product as a
parameter, and based on that I want to retrieve its price, which I do like so with EF:

decimal price = Convert.ToDecimal(db.Products.Where(x => x.Id == productId).Select(x => x.Price));

However, when I click
Add to cart
and hit the url it redirects to, I get this error in VS:

Unable to cast object of type 'System.Data.Entity.Infrastructure.DbQuery`1[System.Decimal]' to type 'System.IConvertible'.

I am new to
so I might not be retrieving the price the right way.

Answer Source
var result = db.Products.FirstOrDefault(x => x.Id == productId);

decimal? price = result?.Price;

Take the product with the specific ID and after that take his price if existing. This syntax is valid if you are using C# 6.0, if you are with previous C# version use: if(result !=null) price = result.Price