![](/img/trans.png)
[英]EF Core database operation throws error "Data may have been modified or deleted since entities were loaded"
[英]Composite primary key and error: data may have been modified or deleted since entities were loaded
我在 Entity Framework Core 中配置了一個帶有復合鍵的鏈接表:
modelBuilder.Entity<TopicArticle>()
.HasKey(ta => new { ta.TopicID, ta.ArticleID });
modelBuilder.Entity<TopicArticle>()
.Property(ta => ta.TopicID).ValueGeneratedNever();
modelBuilder.Entity<TopicArticle>()
.Property(ta => ta.ArticleID).ValueGeneratedNever();
這樣我就可以從應用程序生成此密鑰,這是生成錯誤的應用程序部分:
foreach (var checkBox in model.Topics)
{
TopicArticle ta = context.TopicArticles.AsNoTracking().FirstOrDefault(ta => ta.TopicID == checkBox.Value && ta.ArticleID == model.ArticleID);
if (checkBox.Checked == true)
{
if (ta == null)
{
context.TopicArticles.Add(new TopicArticle() { TopicID = checkBox.Value, ArticleID = model.ArticleID });
}
else
continue;
}
else
{
if (ta == null)
continue;
else
{
context.TopicArticles.Remove(new TopicArticle() { TopicID = checkBox.Value, ArticleID = model.ArticleID });
}
}
}
try
{
context.SaveChanges();
}
catch (Exception ex)
{}
完整的錯誤是:
數據庫操作預計會影響 1 行,但實際上影響了 0 行。 自加載實體以來,數據可能已被修改或刪除。 有關理解和處理樂觀並發異常的信息,請參閱http://go.microsoft.com/fwlink/?LinkId=527962
如何解決這個問題?
您正在嘗試刪除TopicArticle
的new
實例,而不是您之前選擇的引用實例。
更改您的Remove
以使用參考ta
:
context.TopicArticles.Remove(ta);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.