C# MVC3如何更新多个项目的库存
我遵循这个教程 (与此不完全相同) 我正在努力控制库存 创建订单时,我想扣除库存金额(库存-盘点(数量)) 我有三张桌子;订单、订单详细信息和产品 创建OrderDetails列表后,我想修改产品的库存 我不知道如何修改库存?我可以使用类似“db.OrderDetails.Add(OrderDetails)”的命令吗 你能帮我吗?我给你一些编码 请告诉我。谢谢C# MVC3如何更新多个项目的库存,c#,asp.net-mvc,asp.net-mvc-3,linq,C#,Asp.net Mvc,Asp.net Mvc 3,Linq,我遵循这个教程 (与此不完全相同) 我正在努力控制库存 创建订单时,我想扣除库存金额(库存-盘点(数量)) 我有三张桌子;订单、订单详细信息和产品 创建OrderDetails列表后,我想修改产品的库存 我不知道如何修改库存?我可以使用类似“db.OrderDetails.Add(OrderDetails)”的命令吗 你能帮我吗?我给你一些编码 请告诉我。谢谢 public int CreateOrder(Order order) { decimal orderTotal
public int CreateOrder(Order order)
{
decimal orderTotal = 0;
var cartItems = GetCartItems();
// Iterate over the items in the cart, adding the order details for each
foreach (var item in cartItems)
{
var orderDetail = new OrderDetails
{
productId = item.productId,
orderId = order.orderId,
unitPrice = item.priceValue,
rentalPeriod = item.rentalPeriod,
startDate = item.dateCreated.AddDays(2),
endDate = item.dateCreated.AddDays(2 + item.rentalPeriod),
quantity = item.count
};
var productStock = new Product
{ //Is it right coding??
stock = item.Product.stock - item.count
};
// Set the order total of the shopping cart
orderTotal += (item.count * item.priceValue);
//Could be we need some coding here for stock control.
db.OrderDetails.Add(orderDetail);
db.SaveChanges();
}
// Set the order's total to the orderTotal count
order.total = orderTotal;
// Save the order
db.SaveChanges();
// Empty the shopping cart
EmptyCart();
// Return the OrderId as the confirmation number
return order.orderId;
}
视图模型
public class ShoppingCartViewModel
{
public List<Cart> CartItems { get; set; }
public decimal CartTotal { get; set; }
}
命令
这个片段:
var productStock = new Product
{ //Is it right coding??
stock = item.Product.stock - item.count
};
// Set the order total of the shopping cart
orderTotal += (item.count * item.priceValue);
//Could be we need some coding here for stock control.
db.OrderDetails.Add(orderDetail);
db.SaveChanges();
要在创建新产品之前进行库存检查,您可能应该确保您还有剩余的库存,如果没有,请对此采取措施,如下所示:
if (item.Product.stock - item.Count <= 0)
{
//you're out of stock! do something about it here?
}
else
{
//do your code above to create the new Product
}
将其更改为:
item.Product.stock = item.Product.stock - item.count;
这将从产品库存号中减去订购号。然后,当您调用以下行(您已经在代码中这样做了)时,更改将保存到数据库中:
db.SaveChanges();
我的意思是如何更新item.product.stock-item.count?在这个编码之后,如何将扣除的库存保存到product.stock?哦..就是这样吗?这是一个简单的解决办法。非常感谢。呵呵,没问题!享受音乐商店吧,我也是这样开始MVC的,很好的例子:)
if (item.Product.stock - item.Count <= 0)
{
//you're out of stock! do something about it here?
}
else
{
//do your code above to create the new Product
}
var productStock = new Product
{ //Is it right coding??
stock = item.Product.stock - item.count
};
item.Product.stock = item.Product.stock - item.count;
db.SaveChanges();