[英]Composite primary key and error: data may have been modified or deleted since entities were loaded
I configured a link table with a composite key in Entity Framework Core as:我在 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();
So that I can generate this key from app, here is the part of app that generates the error:这样我就可以从应用程序生成此密钥,这是生成错误的应用程序部分:
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)
{}
The full error is:完整的错误是:
Database operation expected to affect 1 row(s) but actually affected 0 row(s).
数据库操作预计会影响 1 行,但实际上影响了 0 行。 Data may have been modified or deleted since entities were loaded.
自加载实体以来,数据可能已被修改或删除。 See http://go.microsoft.com/fwlink/?LinkId=527962 for information on understanding and handling optimistic concurrency exceptions
有关理解和处理乐观并发异常的信息,请参阅http://go.microsoft.com/fwlink/?LinkId=527962
How to resolve this?如何解决这个问题?
You are attempting to remove a new
instance of a TopicArticle
instead of the referenced one that you selected earlier.您正在尝试删除
TopicArticle
的new
实例,而不是您之前选择的引用实例。
Change your Remove
to use the reference ta
:更改您的
Remove
以使用参考ta
:
context.TopicArticles.Remove(ta);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.