public IHttpActionResult PutPortfolioBook(int Id, PortfolioBook portfolioBook) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } if (Id != portfolioBook.Id) { return(BadRequest()); } try { db.PortfolioBooks.Attach(portfolioBook); db.Entry(portfolioBook).State = EntityState.Modified; db.SaveChanges(); db.Entry(portfolioBook).Collection(pb => pb.Items).Load(); //Create a new temporary list to store the items. List <PortfolioItem> tempPortfolioItems = new List <PortfolioItem>(); foreach (var item in portfolioBook.Items) { tempPortfolioItems.Add(item); } //Go through the temporary list, figuring out if we need to add //or update the item. foreach (var item in tempPortfolioItems) { var portItemToDelete = db.PortfolioItems.Where(t => t.Id == item.Id).FirstOrDefault(); //If we found it in the database we need to update it. if (portItemToDelete != null) { //update case db.PortfolioItems.Attach(item); db.Entry(portItemToDelete).State = EntityState.Modified; } //Otherwise we're going to add it. else { //adding db.PortfolioItems.Add(item); } } db.SaveChanges(); return(Ok <PortfolioBook>(portfolioBook)); } catch (Exception ex) { //There was a problem storing the portfolio return(StatusCode(HttpStatusCode.InternalServerError)); } }
public IHttpActionResult PostPortfolioBook(PortfolioBook portfolioBook) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } db.PortfolioBooks.Add(portfolioBook); db.SaveChanges(); return(Ok <PortfolioBook>(portfolioBook)); }
public IHttpActionResult GetPortfolioBook(int Id) { //db.PortfolioBooks.Include(pb => pb.Items). PortfolioBook portfolioBook = db.PortfolioBooks.Find(Id); db.Entry(portfolioBook).Collection(pb => pb.Items).Load(); if (portfolioBook == null) { return(NotFound()); } portfolioBook.Items = portfolioBook.Items.OrderBy(item => item.Order).ToList(); return(Ok(portfolioBook)); }