简体   繁体   中英

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:

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). 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

How to resolve this?

You are attempting to remove a new instance of a TopicArticle instead of the referenced one that you selected earlier.

Change your Remove to use the reference ta :

context.TopicArticles.Remove(ta);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM