【问题标题】:Composite primary key and error: data may have been modified or deleted since entities were loaded复合主键和错误:自加载实体以来数据可能已被修改或删除
【发布时间】:2020-12-20 11:57:26
【问题描述】:

我在 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

如何解决?

【问题讨论】:

  • 也许您可以记录 SQL 查询并直接在 SGBD 上尝试。

标签: c# entity-framework-core


【解决方案1】:

您正在尝试删除 TopicArticle 的 new 实例,而不是您之前选择的引用实例。

更改您的 Remove 以使用引用 ta:

context.TopicArticles.Remove(ta);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-05-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多