我正在处理一个应该将记录从三个表移动到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()方法之前检查了archiveIssue实体,并且其Id字段具有正确的值。表中没有其他记录具有该值。我已经尝试过其他几个版本,包括AsNoTracking(),克隆问题实体或将其状态设置为已删除。
Archive *表确实有一个键,它们被设置为ValueGeneratedNever(),如:
modelBuilder.Entity<ArchiveIssue>()
.HasKey(c => c.Id);
modelBuilder.Entity<ArchiveIssue>()
.Property(c => c.Id)
.ValueGeneratedNever();
ArchiveIssue构造函数只是将源实体中的所有值复制到Archive 1:
public ArchiveIssue(Issue issue) {
this.Id = issue.Id;
this.Code = issue.Code;
this.WeekNo = issue.WeekNo;
this.WeekCount = issue.WeekCount;
this.CreateDate = issue.CreateDate;
...
}
答案 0 :(得分:0)
错误消息只是许多错误的首要问题,主要原因是: