我正在制作购物车,点击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
的新手,所以我可能不会以正确的方式检索价格。
答案 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