EF在插入和更新子表记录时给出错误

时间:2020-03-23 10:16:06

标签: c# asp.net-core entity-framework-core asp.net-core-mvc

内部故事对象我具有子对象评分,插入新评分时出现问题。

Errrr消息为“数据库操作预期会影响1行,但实际上影响0行。自加载实体以来,数据可能已被修改或删除。”

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 :(得分:0)

您正在异步运行,因此它不会等待您需要使其同步的提交