我正在研究一个函数,该函数应该将记录从三个表移动到它们的 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 构造函数只是将所有值从源实体复制到存档一:
public ArchiveIssue(Issue issue) {
this.Id = issue.Id;
this.Code = issue.Code;
this.WeekNo = issue.WeekNo;
this.WeekCount = issue.WeekCount;
this.CreateDate = issue.CreateDate;
...
}
错误消息只是许多错误的首要原因,主要原因是:
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句