[英]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.