EF giving error on inserting and updating child table record

asp.net-core asp.net-core-mvc c# entity-framework-core

Question

Inside story object i have child object rating i am getting issue while inserting new rating.

Erorr Message is "Database operation expected to affect 1 row(s) but actually affected 0 row(s). Data may have been modified or deleted since entities were loaded."

enter image description here

   public async Task WriteRatingForStory(int storyId, int userId, int 
      score)
    {
        // Get the story that was rated
        var story = await _dbContext.Stories.FirstOrDefaultAsync(story => story.Id == storyId);

        // Updating thestory with the new rating
        story.WriteRating(userId, score);

        //_dbContext.Stories.Update(story);

        // Save the updated story to the database
        var saved = false;
        while (!saved)
        {
            try
            {
                // Attempt to save changes to the database

                _dbContext.SaveChanges();
                saved = true;
            }
            catch (DbUpdateConcurrencyException ex)
            { 
            }
         }
      } 

   public void WriteRating(int userId, double newRating)
       {

            Ratings.Add(new Rating() { StoryId = this.Id, Score = newRating, UserId = userId });
            AverageRating = ((AverageRating * NumberOfRatings - 1) + newRating) / NumberOfRatings;

    }
1
0
3/23/2020 3:27:42 PM

Popular Answer

You are running asynchronised, so it doesn't wait for the commit you need to make it sync

0
3/23/2020 10:38:00 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow