2012-04-02 64 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」字段中選擇的第一個項目這樣做。