public void Create(Customer customer, string createdById = null) { // If the customer created by Id does not equal null, but the id specified does not exist if (customer.CreatedById != null && !_context.Users.Any(e => e.Id == customer.CreatedById)) { throw new UserNotFoundException(); } // Assign the Slug customer.Slug = customer.CompanyName.GenerateSlug(); // If the Company Name Or Slug already exist, throw Exception if (_context.Customers.Any(e => e.CompanyName.Equals(customer.CompanyName) || e.Slug.Equals(customer.Slug))) { throw new CompanyAlreadyExistsException(); } // Assign the created by id customer.CreatedById = createdById; // Add to the table _context.Customers.Add(customer); // Save changes _context.SaveChanges(); }
public void EditCustomer(Customer customer) { // Attach to context if for some reason it is not if (_context.Entry(customer).State == EntityState.Detached) _context.Customers.Attach(customer); // Reslugify // TODO find a way to see if the CompanyName is actually a dirty field customer.Slug = customer.CompanyName.GenerateSlug(); // Check to see if another company has the same company name if (DoesCustomerExist(customer)) { throw new CompanyAlreadyExistsException(); } // Make it dirty _context.Entry(customer).State = EntityState.Modified; _context.SaveChanges(); }
public OrderCreateViewModel OrderCreateFactory( Customer customer, List<Product> products, OrderCreateViewModel vm = null) { // Check if the view model exists, if not create new one vm = vm ?? new OrderCreateViewModel(); // Assign the order details if it exists or create new one vm.Order = vm.Order ?? new OrderViewModel(); // Products var productsList = products.Select( e => new OrderProductViewModel { ProductId = e.ProductId, ProductName = e.ProductName, Price = e.UnitPrice, SupplierName = e.Supplier.CompanyName, Qauntity = 0 }).ToList(); // Reassign products with proper quanities vm.Products?.ForEach(e => { if (e.Qauntity <= 0) return; var orderProductViewModel = productsList.FirstOrDefault(x => x.ProductId == e.ProductId); if (orderProductViewModel != null) orderProductViewModel.Qauntity = e.Qauntity; }); vm.Products = productsList; vm.Customer = customer; return vm; }
&& e.CustomerId != customer.CustomerId); // With Different ID public async Task DeleteCustomerAsync(Customer customer) { // Something went wrong, throw exception if (customer == null) throw new CustomerNotFoundException(); _context.Customers.Remove(customer); await _context.SaveChangesAsync(); }
private bool DoesCustomerExist(Customer customer) => _context.Customers.Any(e => (e.CompanyName.Equals(customer.CompanyName) // Same Company Name || e.Slug.Equals(customer.Slug)) // Or Some Slug && e.CustomerId != customer.CustomerId); // With Different ID