I'm working on a function that is supposed to move records from three tables to their Archive* versions. 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. 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.
Archive* tables does have a key and they are set to ValueGeneratedNever() like:
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:
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:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.