} // Get by ID /// <summary> /// Adds a Store Rating /// </summary> /// <param name="storeRating"></param> /// <returns></returns> public IHttpActionResult Post(StoreRatingCreate storeRating) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var service = CreateStoreRatingService(); if (!service.CreateStoreRating(storeRating)) { return(InternalServerError()); } return(Ok()); } // Post
public bool CreateStoreRating(StoreRatingCreate model) { // format the new StoreRating record var entity = new StoreRating() { OwnerId = _userId, StoreId = model.StoreId, StoreIndividualRating = model.StoreIndividualRating, Store = model.Store }; // Add the new StoreRating to the table using (var ctx = new ApplicationDbContext()) { ctx.StoreRatings.Add(entity); bool addedStoreRating = ctx.SaveChanges() == 1; if (!addedStoreRating) { return(false); } } // Update the Store record using (var ctx = new ApplicationDbContext()) { // retrieve the StoreRating record we just posted so we can follow the foreign key to the Store record var newStoreRating = ctx .StoreRatings .Single(e => e.StoreRatingId == entity.StoreRatingId && e.OwnerId == _userId); // Update the fields in the Store record at the other end of the foreign key newStoreRating.Store.CulumativeRating += model.StoreIndividualRating; newStoreRating.Store.NumberOfRatings += 1; newStoreRating.Store.StoreRating = newStoreRating.Store.CulumativeRating / newStoreRating.Store.NumberOfRatings; return(ctx.SaveChanges() == 1); } } // CreateStoreRating