The instance of entity type cannot be tracked because another instance with the same key value for {'Id'} is already being tracked

c# entity-framework-core


I'm working on a function that is supposed to move records from three tables to their Archive* versions. The tables are Issues, Actions, Attachments. First I get all records from the three tables, then make their Archive versions and attach these to the context:

var issue = _ctx.Issues.FirstOrDefault(x=>x.Id == issueId);
var actions = _ctx.Actions.Where(x=>x.IssueId == issueId).ToList();
var attachments = _ctx.Attachments.Where(x=>x.IssueId == issueId).ToList();

await _ctx.SaveChangesAsync();

var archiveIssue = new ArchiveIssue(issue);
_ctx.ArchiveIssues.Add(archiveIssue); // this line throws the exception
_ctx.ArchiveActions.AddRange(actions.Select(x=>new ArchiveAction(x)));
_ctx.ArchiveAttachments.AddRange(attachments.Select(x=>new ArchiveAttachment(x)));
await _ctx.SaveChangesAsync();


I've checked the archiveIssue entity before the Add() method and its Id field has the proper value. There are no other records in the table with that value. I've already tried several other version, including AsNoTracking(), cloning the issue entity, or setting its state to Deleted.

Archive* tables does have a key and they are set to ValueGeneratedNever() like:

        .HasKey(c => c.Id);

        .Property(c => c.Id)

ArchiveIssue constructor just copies all values from the source entity to the Archive one:

public ArchiveIssue(Issue issue) {
        this.Id = issue.Id;
        this.Code = issue.Code;     
        this.WeekNo = issue.WeekNo;
        this.WeekCount = issue.WeekCount;
        this.CreateDate = issue.CreateDate;
3/1/2018 2:15:36 PM

Accepted Answer

The error message was just the top of many errors and the main causes were:

  • I had a foreign key in ArchiveAttachment to the original Issue (not the archive one). This caused that the entity of ArchiveAttachment created then deleted immediately because of cascade delete set in the FK property.
  • Had a similar error in ArchiveActions: I had a this.Issue = action.Issue line in ArchiveAction's ctor and that action.Issue was just the original Issue not the Archive one which is deleted in the next step.
  • The op error was thrown by the cross foreign key I think but I don't understand exactly why. Anyway after fixing the FK it's gone.
3/2/2018 9:18:04 AM

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow