public void CreateOrUpdate(OrderBindingModel model) { using (var context = new ElectronicsShopDatabase()) { Order tempOrder = model.Id.HasValue ? null : new Order(); if (model.Id.HasValue) { tempOrder = context.Orders.FirstOrDefault(rec => rec.Id == model.Id); } using (var transaction = context.Database.BeginTransaction()) { try { if (model.Id.HasValue) { if (tempOrder == null) { throw new Exception("Элемент не найден"); } CreateModel(model, tempOrder); context.SaveChanges(); } else { Order order = CreateModel(model, tempOrder); context.Orders.Add(order); context.SaveChanges(); var groupProducts = model.Products .GroupBy(rec => rec.ProductId) .Select(rec => new { ProductId = rec.Key, Count = rec.Sum(r => r.Count) }); foreach (var groupProduct in groupProducts) { context.OrderProducts.Add(new OrderProduct { OrderId = order.Id, ProductId = groupProduct.ProductId, Count = groupProduct.Count }); context.SaveChanges(); } } transaction.Commit(); } catch (Exception) { transaction.Rollback(); throw; } } } }
public void CreateOrUpdate(ProductBindingModel model) { using (var context = new ElectronicsShopDatabase()) { Product tempProduct = model.Id.HasValue ? null : new Product(); if (model.Id.HasValue) { tempProduct = context.Products.FirstOrDefault(rec => rec.Id == model.Id); } if (model.Id.HasValue) { if (tempProduct == null) { throw new Exception("Элемент не найден"); } CreateModel(model, tempProduct); } else { context.Products.Add(CreateModel(model, tempProduct)); } context.SaveChanges(); } }
public void Delete(ProductBindingModel model) { using (var context = new ElectronicsShopDatabase()) { Product element = context.Products.FirstOrDefault(rec => rec.Id == model.Id.Value); if (element != null) { context.Products.Remove(element); context.SaveChanges(); } else { throw new Exception("Элемент не найден"); } } }