} // Get by ID /// <summary> /// Adds a new Album Rating /// </summary> /// <param name="albumRating"></param> /// <returns></returns> public IHttpActionResult Post(AlbumRatingCreate albumRating) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var service = CreateAlbumRatingService(); if (!service.CreateAlbumRating(albumRating)) { return(InternalServerError()); } return(Ok()); } // Post
public bool CreateAlbumRating(AlbumRatingCreate model) { // format the new AlbumRating record var entity = new AlbumRating() { OwnerId = _userId, AlbumId = model.AlbumId, AlbumIndividualRating = model.AlbumIndividualRating, Album = model.Album }; // Add the new AlbumRating to the table using (var ctx = new ApplicationDbContext()) { ctx.AlbumRatings.Add(entity); bool addedAlbumRating = ctx.SaveChanges() == 1; if (!addedAlbumRating) { return(false); } } // Update the Album record using (var ctx = new ApplicationDbContext()) { // retrieve the AlbumRating record we just posted so we can follow the foreign key to the Album record var newAlbumRating = ctx .AlbumRatings .Single(e => e.AlbumRatingId == entity.AlbumRatingId && e.OwnerId == _userId); // Update the fields in the Album record at the other end of the foreign key newAlbumRating.Album.CulumativeRating += model.AlbumIndividualRating; newAlbumRating.Album.NumberOfRatings += 1; newAlbumRating.Album.Rating = newAlbumRating.Album.CulumativeRating / newAlbumRating.Album.NumberOfRatings; return(ctx.SaveChanges() == 1); } } // CreateAlbumRating