【发布时间】:2020-03-23 10:16:06
【问题描述】:
Inside story object 我有子对象评级我在插入新评级时遇到问题。
错误消息是“数据库操作预计会影响 1 行,但实际上影响了 0 行。自加载实体以来,数据可能已被修改或删除。”
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