开发者

cast iqueryable

how do i cast to cartItem?

              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);

next solution gives me this error >

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

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

ERROR:No coercion operator is defined between types '<>f__AnonymousType2`3[System.Int32,System.Int32,System.String]' and 'CartItem'.

how about this code : this makes error too

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

            // get t开发者_运维技巧he 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);

error : Cannot add an entity with a key that is already in use.


Direct casting isn't really feasible - you'll probably want to make that SELECT create a new CartItem instead of an anonymous type.

EDIT: By which I mean, try something like:

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);

This is assuming your CartItem class has an empty constructor - obviously you can adapt the SELECT as necessary.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜