public static void modifyOrder(List <Order> orderList, string orderNo, Order o) //修改订单 { int i = 0; for (i = 0; i < orderList.Count; i++) { if (orderList[i].OrderNo == orderNo) { orderList[i] = o; break; } } if (i == orderList.Count) { Exception e = new Exception($"找不到订单{orderNo}。"); throw e; } using (var context = new OrderingContext()) //在数据库中修改order { var orderdb = context.OrderforDBs.Include("ItemforDBs").FirstOrDefault(p => p.orderNo == orderNo); if (orderdb != null) { orderdb.orderNo = o.OrderNo; orderdb.clientName = o.Clients.Name; orderdb.total = o.Total; var itemdb = context.ItemforDBs.Where(p => p.OrderforDBId == orderdb.OrderforDBId); //参照完整性约束,先删除原item if (itemdb != null) { foreach (var item in itemdb) { context.ItemforDBs.Remove(item); } } context.SaveChanges(); orderdb.ItemforDBs = new List <ItemforDB>(); foreach (OrderItem item in o.OrderItemList) //添加新item,重新将新item加入orderlist { ItemforDB itemfordb = new ItemforDB() { productName = item.Products.Name, price = item.price, count = item.Number, total = item.Total }; orderdb.ItemforDBs.Add(itemfordb); } context.SaveChanges(); } } }
public static void addOrder(List <Order> orderList, Order o) //添加订单 { foreach (Order x in orderList) { if (x.Equals(o)) { return; } } orderList.Add(o); sort(orderList); //添加后按订单号排序 using (var context = new OrderingContext()) //将新order加入数据库 { var orderdb = new OrderforDB { orderNo = o.OrderNo, clientName = o.Clients.Name, dateTime = o.OrderDate.ToString(), total = o.Total }; orderdb.ItemforDBs = new List <ItemforDB>(); foreach (OrderItem oi in o.OrderItemList) //对order的itemlist赋值 { ItemforDB itemfordb = new ItemforDB() { productName = oi.Products.Name, price = oi.price, count = oi.Number, total = oi.Total }; orderdb.ItemforDBs.Add(itemfordb); } context.OrderforDBs.Add(orderdb); context.SaveChanges(); } }