} // Get by ID /// <summary> /// Adds a Song Rating /// </summary> /// <param name="songRating"></param> /// <returns></returns> public IHttpActionResult Post(SongRatingCreate songRating) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var service = CreateSongRatingService(); if (!service.CreateSongRating(songRating)) { return(InternalServerError()); } return(Ok()); } // Post
public bool CreateSongRating(SongRatingCreate model) { // format the new SongRating record var entity = new SongRating() { OwnerId = _userId, SongId = model.SongId, SongIndividualRating = model.SongIndividualRating, Song = model.Song }; // Add the new SongRating to the table using (var ctx = new ApplicationDbContext()) { ctx.SongRatings.Add(entity); bool addedSongRating = ctx.SaveChanges() == 1; if (!addedSongRating) { return(false); } } // Update the Song record using (var ctx = new ApplicationDbContext()) { // retrieve the SongRating record we just posted so we can follow the foreign key to the Song record var newSongRating = ctx .SongRatings .Single(e => e.SongRatingId == entity.SongRatingId && e.OwnerId == _userId); // Update the fields in the Song record at the other end of the foreign key newSongRating.Song.CulumativeRating += model.SongIndividualRating; newSongRating.Song.NumberOfRatings += 1; newSongRating.Song.Rating = newSongRating.Song.CulumativeRating / newSongRating.Song.NumberOfRatings; return(ctx.SaveChanges() == 1); } } // CreateSongRating