我的 CartItems 表中有以下记录:
当我迁移购物车时,我想将两条记录合并为一条,购物车 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();
}
}