![](/img/trans.png)
[英]The instance of entity type 'Entity' cannot be tracked because another instance with the same key value for {'Id'} is already being tracked
[英]The instance of entity type <T> cannot be tracked because another instance with the same key value for {'Id'} is already being tracked
我正在使用一个功能,该功能应该将记录从三个表移至其Archive *版本。 这些表是问题,操作,附件。 首先,我从三个表中获取所有记录,然后创建其存档版本并将其附加到上下文:
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();
在Add()方法及其ID字段具有正确的值之前,我已经检查了archiveIssue实体。 表中没有其他具有该值的记录。 我已经尝试过其他几个版本,包括AsNoTracking(),克隆问题实体或将其状态设置为“已删除”。
Archive *表确实具有键,并且将它们设置为ValueGeneratedNever(),例如:
modelBuilder.Entity<ArchiveIssue>()
.HasKey(c => c.Id);
modelBuilder.Entity<ArchiveIssue>()
.Property(c => c.Id)
.ValueGeneratedNever();
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;
...
}
该错误消息只是许多错误的开头,主要原因是:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.