将两个记录合并为一个并更新列

时间:2013-05-21 13:34:46

标签: linq entity-framework

我的CartItems表中有以下记录:

enter image description here

当我迁移购物车时,我想将两个记录合并为一个购物车ID为Test1,然后将数量更新为2.

所以它将是CartItemId 84,CartId Test1,Quantity 2,DateCreated 5/21/2013,ProductId 16

我如何在linq / EF中执行此操作?

修改

 public void MigrateCart(string userName)
    {
        ShoppingCartId = GetCartId();

        var shoppingCart = _context.ShoppingCartItems.Where(c => c.CartId == ShoppingCartId);

        foreach (var item in shoppingCart)
        {
            item.CartId = userName;
        }

        _context.SaveChanges();

    }

修改

我想我拥有它。

public void MigrateCart(string userName)
    {
        ShoppingCartId = GetCartId();

        if (ShoppingCartId != userName)
        {
            var shoppingCart = _context.ShoppingCartItems.Where(c => c.CartId == ShoppingCartId).ToList();
            var userShoppingCartItems = _context.ShoppingCartItems.Where(c => c.CartId == userName).ToList();

            foreach (var item in shoppingCart)
            {
                foreach (var userShoppingCartItem in userShoppingCartItems)
                {
                    if (item.ProductId == userShoppingCartItem.ProductId)
                    {
                        item.Quantity += userShoppingCartItem.Quantity;
                        item.CartId = userName;
                        _context.ShoppingCartItems.Remove(userShoppingCartItem);
                    }
                }
                item.CartId = userName;
            }

            _context.SaveChanges();

        }
        else
        {
            var shoppingCart = _context.ShoppingCartItems.Where(c => c.CartId == ShoppingCartId);

            foreach (var item in shoppingCart)
            {
                item.CartId = userName;
            }

            _context.SaveChanges();
        }

    }

1 个答案:

答案 0 :(得分:0)

因为你不问如何获得这两个项目,我只是给你一个非常质朴的方式。

var item1 = context.CartItems.FirstOrDefault(m => m.Id == 84);
var item2 = context.CartItems.FirstOrDefault(m => m.Id == 85);

item1.Quantity += item2.Quantity;//add quantity of item2 to item1
context.CartItems.Remove(item2);//remove item2
context.SaveChanges();