public async Task <IHttpActionResult> PostProductType(ProductTypeDetailsDto productTypeDetails) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var workwrok = productTypeDetails.ProductGroups; List <ProductGroup> productGroups = new List <ProductGroup>(); foreach (var i in workwrok) { var pG = from pg in db.ProductGroups where pg.Id == i select pg; pG.ForEach(pg => productGroups.Add(pg)); } var productType = new ProductType { Color = productTypeDetails.Color, Name = productTypeDetails.Name, Price = productTypeDetails.Price }; productGroups?.ForEach(e => productType.ProductGroups.Add(e)); db.ProductTypes.Add(productType); await db.SaveChangesAsync(); productTypeDetails.Id = productType.Id; return(CreatedAtRoute("DefaultApi", new { id = productTypeDetails.Id }, productTypeDetails)); }
public async Task <IHttpActionResult> PutProductType(int id, ProductTypeDetailsDto productTypeDetails) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var ProductGroupList = productTypeDetails.ProductGroups; List <ProductGroup> productGroups = new List <ProductGroup>(); foreach (var i in ProductGroupList) { var pG = from pg in db.ProductGroups where pg.Id == i select pg; pG.ForEach(pg => productGroups.Add(pg)); } var productType = db.ProductTypes.Find(id); if (productType != null) { productType.Color = productTypeDetails.Color; productType.Name = productTypeDetails.Name; productType.Price = productTypeDetails.Price; } productType.ProductGroups.Clear(); productGroups?.ForEach(e => productType.ProductGroups.Add(e)); if (id != productType.Id) { return(BadRequest()); } db.Set <ProductType>().Attach(productType); db.Entry(productType).State = EntityState.Modified; try { await db.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!ProductTypeExists(id)) { return(NotFound()); } else { throw; } } return(StatusCode(HttpStatusCode.NoContent)); }
public async Task <IHttpActionResult> GetProductType(int id) { ProductType productType = await db.ProductTypes.Include(pt => pt.ProductGroups).SingleOrDefaultAsync(pt => pt.Id == id); if (productType == null) { return(NotFound()); } var productTypeDto = new ProductTypeDetailsDto { Color = productType.Color, Name = productType.Name, Id = productType.Id, Price = productType.Price, ProductGroups = new List <long>() }; productType.ProductGroups.ForEach(pt => productTypeDto.ProductGroups.Add(pt.Id)); return(Ok(productTypeDto)); }