[英]The instance of entity type <T> cannot be tracked because another instance with the same key value for {'Id'} is already being tracked
I'm working on a function that is supposed to move records from three tables to their Archive* versions. 我正在使用一个功能,该功能应该将记录从三个表移至其Archive *版本。 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();
_ctx.Attachments.RemoveRange(attachments);
_ctx.Actions.RemoveRange(actions);
_ctx.Issues.Remove(issue);
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();
trx.Commit();
I've checked the archiveIssue entity before the Add() method and its Id field has the proper value. 在Add()方法及其ID字段具有正确的值之前,我已经检查了archiveIssue实体。 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.
我已经尝试过其他几个版本,包括AsNoTracking(),克隆问题实体或将其状态设置为“已删除”。
Archive* tables does have a key and they are set to ValueGeneratedNever() like: Archive *表确实具有键,并且将它们设置为ValueGeneratedNever(),例如:
modelBuilder.Entity<ArchiveIssue>()
.HasKey(c => c.Id);
modelBuilder.Entity<ArchiveIssue>()
.Property(c => c.Id)
.ValueGeneratedNever();
ArchiveIssue constructor just copies all values from the source entity to the Archive one: ArchiveIssue构造函数只是将所有值从源实体复制到Archive一个:
public ArchiveIssue(Issue issue) {
this.Id = issue.Id;
this.Code = issue.Code;
this.WeekNo = issue.WeekNo;
this.WeekCount = issue.WeekCount;
this.CreateDate = issue.CreateDate;
...
}
The error message was just the top of many errors and the main causes were: 该错误消息只是许多错误的开头,主要原因是:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.