【问题标题】:EF giving error on inserting and updating child table recordEF 在插入和更新子表记录时出错
【发布时间】:2020-03-23 10:16:06
【问题描述】:

Inside story object 我有子对象评级我在插入新评级时遇到问题。

错误消息是“数据库操作预计会影响 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;

    }

【问题讨论】:

  • 他有什么错误?图片不显示?
  • 我不确定这是否会导致错误,但不需要_dbContext.Update(story)。该故事已附加到_dbContext(已从中读取),因此对其或相关对象的任何更改都将自动写入SaveChanges()上的数据库。
  • 错误消息显示“数据库操作预计会影响 1 行,但实际上影响了 0 行。由于加载实体,数据可能已被修改或删除。”
  • 可以用 await _dbcontext.saveasync();

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


【解决方案1】:

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

【讨论】:

  • 根据您的建议实施了更改,但它不起作用
  • 我更新了代码描述,即使您可以查看图像以获取更多详细信息i.stack.imgur.com/OegCQ.png
  • 我会尝试 await context.SaveChangesAsync();而不是 context.SaveChanges();
猜你喜欢
  • 2019-03-14
  • 1970-01-01
  • 2013-02-06
  • 1970-01-01
  • 2021-03-31
  • 1970-01-01
  • 2017-04-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多