2012-04-02 66 views
3

我想在MVC3项目中使用LINQ获取十进制值。通过LINQ选择十进制值

我该如何得到它?它看起来很容易的问题,但我不能得到一个单一的十进制值,而不是列表Product.aWeekPrice。

如何获得特定的threeDayPrice?越来越threeDayPrice后,它将被应用于如果条件给予不同的条件下,你可以在我下面的代码中看到:

public decimal GetTotal(decimal price) 
    { 
     // Multiply product price by count of that album to get 
     // the current price for each of those product in the cart 
     // sum all product price totals to get the cart total 

     //In select part, I have got error, 'cannot convert type 
     //'System.Linq.IQueryable<decimal>' to 'decimal' 

     decimal threeDayPrice = (from cartItems in db.Cart 
           where cartItems.cartId == ShoppingCartId 
           select (decimal)cartItems.Product.threeDayPrice); 

     decimal aWeekPrice = (from cartItems in db.Cart 
           where cartItems.cartId == ShoppingCartId 
           select (decimal)cartItems.Product.aWeekPrice); 

     if (price == threeDayPrice) 
     { 
      decimal? total = (from cartItems in db.Cart 
           where cartItems.cartId == ShoppingCartId 
           select (int?)cartItems.count * cartItems.Product.threeDayPrice).Sum(); 
      return total ?? decimal.Zero; 
     } 

     else if (price == aWeekPrice) 
     { 
      decimal? total = (from cartItems in db.Cart 
           where cartItems.cartId == ShoppingCartId 
           select (int?)cartItems.count * cartItems.Product.aWeekPrice).Sum(); 
      return total ?? decimal.Zero; 
     }   
    } 
+0

threeDayPrice/aWeekPrice的数据类型是什么?它们是小数集合,还是小数? – McGarnagle 2012-04-02 04:43:32

+0

这个问题与MVC无关。这是一个数据库问题,所以它是Entity Framework或Linq to Sql,不知道哪个 – 2012-04-02 05:07:13

回答

5

如果查询总是只返回一个值使用.Single()把它作为decimal代替小数的集合。

decimal threeDayPrice = (from cartItems in db.Cart 
          where cartItems.cartId == ShoppingCartId 
          select (decimal)cartItems.Product.threeDayPrice).Single(); 

    decimal aWeekPrice = (from cartItems in db.Cart 
          where cartItems.cartId == ShoppingCartId 
          select (decimal)cartItems.Product.aWeekPrice).Single(); 

如果有可能的是,查询将返回一个以上或零元素使用First()/FirstOrDefault()代替。

+0

谢谢你的回复,但是当我把.Single()或First()或FirstOr Default()时,发生公共十进制错误GetTotal十进制价格)。它是说'不是所有的代码路径都返回一个值'。这是什么意思? – wholee1 2012-04-02 06:47:18

+0

这不是LINQ错误。在你的方法中,当('price!= threeDayPrice和price!= aWeekPrice')(没有if语句它会被执行的时候)没有返回值。您应该在方法的末尾添加'return decimal.Zero;'。 – MarcinJuraszek 2012-04-02 06:50:28

+0

谢谢你的好意!谢谢。 – wholee1 2012-04-02 06:58:11

3

该错误消息表明cartItems.Product.aWeekPrice是一个集合,而不是一个集合。所以,你只需要选择你需要的任何项目。例如:

decimal threeDayPrice = (from cartItems in db.Cart 
        where cartItems.cartId == ShoppingCartId 
        select (decimal)cartItems.Product.threeDayPrice).FirstOrDefault(); 

应该删除错误信息,但它会通过在“threeDayPrice”字段中选择的第一个项目这样做。