从表中获取小数

时间:2016-11-11 17:58:45

标签: c# asp.net-mvc entity-framework

我正在制作购物车,点击Add to cart后,用户被重定向到接受产品id作为GET参数的页面,并根据我想要的内容检索它的价格,我喜欢EF:

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

但是,当我点击Add to cart并点击重定向到的网址时,我在VS中收到此错误:

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

我是.NET的新手,所以我可能不会以正确的方式检索价格。

1 个答案:

答案 0 :(得分:2)

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

decimal? price = result?.Price;

使用具有特定ID的产品,然后取出其价格(如果存在)。如果您使用C# 6.0,则此语法有效,如果您使用以前的C#版本:if(result !=null) price = result.Price