public async Task<IHttpActionResult> PutProductGroup(long id, ProductGroupDetailsDto productGroupDetails) { if (!ModelState.IsValid) { return BadRequest(ModelState); } var ProductList = productGroupDetails.Products; List<Product> products = new List<Product>(); foreach (var i in ProductList) { var product = from pr in db.Products where pr.Id == i select pr; product.ForEach(pr => products.Add(pr)); } var productGroup = db.ProductGroups.Find(id); if (productGroup != null) { productGroup.Name = productGroupDetails.Name; } productGroup.Products.Clear(); products?.ForEach(e=> productGroup.Products.Add(e)); if (id != productGroup.Id) { return BadRequest(); } db.Set<ProductGroup>().Attach(productGroup); db.Entry(productGroup).State = EntityState.Modified; try { await db.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!ProductGroupExists(id)) { return NotFound(); } else { throw; } } return StatusCode(HttpStatusCode.NoContent); }
public async Task<IHttpActionResult> GetProductGroup(long id) { ProductGroup productGroup = await db.ProductGroups.Include(pg => pg.Products).SingleOrDefaultAsync(pg => pg.Id == id); if (productGroup == null) { return NotFound(); } var productGroupDetailsDto = new ProductGroupDetailsDto() {Id = productGroup.Id, Name = productGroup.Name, Products = new List<long>()}; productGroup.Products.ForEach(p => productGroupDetailsDto.Products.Add(p.Id)); return Ok(productGroupDetailsDto); }
public async Task<IHttpActionResult> PostProductGroup(ProductGroupDetailsDto productGroupDetails) { if (!ModelState.IsValid) { return BadRequest(ModelState); } var workwrok = productGroupDetails.Products; List<Product> products = new List<Product>(); foreach (var i in workwrok) { var p = from pt in db.Products where pt.Id == i select pt; p.ForEach(pr => products.Add(pr)); } var productGroup = new ProductGroup { Name = productGroupDetails.Name }; products?.ForEach(e => productGroup.Products.Add(e)); db.ProductGroups.Add(productGroup); await db.SaveChangesAsync(); productGroupDetails.Id = productGroup.Id; return CreatedAtRoute("DefaultApi", new { id = productGroupDetails.Id }, productGroupDetails); }