public OrderProduct(Entities.OrderProduct model) { this.OrderProductId = model.OrderProductId; this.OrderId = model.Order.OrderId; if (model.Product != null) { this.ProductId = model.Product.ProductId; } this.Quantity = model.Quantity; }
public async Task <ActionResult <Object> > CreateOrder(Models.Order model) { try { var user = this.GetUser(); if (user != null) { var address = this._dbContext.Addresses.FirstOrDefault(addr => addr.AddressId == model.AddressId); if (address == null) { return(BadRequest(new { message = "Address is empty" })); } Order newOrder = new Entities.Order() { User = user, IssueDate = DateTime.UtcNow, Price = model.Price, Address = address, OrderProducts = new List <Entities.OrderProduct>() }; await this._dbContext.Orders.AddAsync(newOrder); await this._dbContext.SaveChangesAsync(); if (model.OrderProducts.Count > 0) { foreach (Models.OrderProduct op in model.OrderProducts) { var product = await this._dbContext.Products.FirstOrDefaultAsync(p => p.ProductId == op.ProductId); if (product != null) { Entities.OrderProduct orderProduct = new Entities.OrderProduct() { Order = newOrder, Product = product, Quantity = op.Quantity, }; await this._dbContext.OrderProducts.AddAsync(orderProduct); } } } int result = await this._dbContext.SaveChangesAsync(); if (result > 0) { return(Ok()); } else { return(BadRequest()); } } else { return(BadRequest()); } } catch (Exception ex) { this._logger.LogError(ex, "CreateOrder Failed"); return(BadRequest()); } }