2011-05-27 6 views
0

どのように私はカートにキャストするのですか?キャストiqueryable

   var newItem = from i in dc.CartItems 
           where i.productID == item.productID 
           select new {productID = i.productID, 
              Quantity = i.Quantity + item.Quantity , 
              cartID = item.cartID }; 

      CartItem itemToUpdate = (here??)newItem; 
      dc.CartItems.Attach(itemToUpdate, true); 

次のソリューションは、私は、このエラー>

ERRORいます:いいえ強制演算子は型の間で定義されていない '<> f__AnonymousType2`3 [可能System.Int32、可能System.Int32、可能System.String]'と 'カートアイテム'。

どのようにこのコードについて:これはエラーあまりに

  if (IfExist(item)) 
     { 
      //if this product id in cart 

      // get the quantity of existing cartItem 
      int quantity = (from i in dc.CartItems 
        where i.productID == item.productID 
        select i).First().Quantity; 

      // sum quanitities of existing and just inserted item 

      item.Quantity += quantity; 

      dc.CartItems.Attach(item, true); 

エラーになります:既に使用されているキーを持つエンティティを追加することはできません。

+0

申し訳ありませんが、わたしはこれまでにできるほど明確ではありませんでした。私の答えを更新して、私が意味するものの例を挙げました。 – reavowed

+0

添付の際にアイテムを更新するのはなぜですか?そのエラー – freeTayyeb

答えて

1

ダイレクトキャスティングは実用的ではありません。おそらく、SELECTが匿名型ではなく新しいCartItemを作成するようにしたいと思うでしょう。

EDIT:これはあなたのCartItemクラスが空のコンストラクタを持っていると仮定している

List<CartItem> newItem = (from i in dc.CartItems 
          where i.productID == item.productID 
          select new CartItem {productID = i.productID, 
               Quantity = i.Quantity + item.Quantity , 
               cartID = item.cartID }) 

CartItem itemToUpdate = newItem.First(); 
dc.CartItems.Attach(itemToUpdate, true); 

- 明らかにあなたは、必要に応じてSELECTを適応させることができます:私は意味それによって、のようなものを試してみてください。

+0

このコードはあまりにもエラーになります – freeTayyeb