public void UpdateOrder(Order order) { using (var context = new GiaikhatNgocMaiEntities()) { var dbItemList = context.OrderDetails.Where(i => i.OrderId == order.Id).OrderBy(i => i.Id); var newItemList = order.OrderDetails.OrderBy(i => i.Id).ToList(); foreach (var dt in dbItemList) { var existedItem = newItemList.SingleOrDefault(i => i.Id == dt.Id); if (existedItem == null) { context.Entry(dt).State = System.Data.Entity.EntityState.Deleted; continue; } context.Entry(dt).State = System.Data.Entity.EntityState.Modified; newItemList.Remove(existedItem); } newItemList.Select(i => context.Entry(i).State = System.Data.Entity.EntityState.Added); context.Entry(order).State = System.Data.Entity.EntityState.Modified; context.SaveChanges(); } }
public string CreateOrder(Order order) { using (var context = new GiaikhatNgocMaiEntities()) { if (order.OrderDetails.Count <= 0) throw new Exception(); context.Orders.Add(order); context.SaveChanges(); context.Entry(order).Reload(); return order.OrderNumber; } }