我正在尝试使用循环输入数据。在第一个循环中,它能够成功地输入数据。在第二个循环中,当保存数据时,会出现一个错误消息
An exception of type 'System.InvalidOperationException' occurred in Microsoft.EntityFrameworkCore.dll
but was not handled in user code:
'The property 'userTask.TaskScheduleId' is part of a key and so cannot be modified or marked as modified.
To change the principal of an existing
entity with an identifying foreign key, first delete the dependent and invoke 'SaveChanges', and then
associate the dependent with the new principal.'
下面是代码。它在taskSchedule中创建数据的副本,然后将其复制到所有其他用户。taskSchedule表与users表有多对多的关系,这就是为什么它也在userTask表中保存数据。
foreach(int user in users){
TaskSchedule copyTaskSchedule = new TaskSchedule();
copyTaskSchedule = taskSchedule;
copyTaskSchedule.Id = 0;
copyTaskSchedule.Notes = null;
copyTaskSchedule.UserTasks = null;
_context.TaskSchedules.Add(copyTaskSchedule);
_context.SaveChanges(); // this is where the code stops on the 2nd loop
// add updated user to the task
userTask copyUserTask = new userTask();
copyUserTask.TaskScheduleId = copyTaskSchedule.Id;
copyUserTask.UserId = user;
_context.userTasks.Add(copyUserTask);
_context.SaveChanges();
}
TaskSchedule模型public class TaskSchedule
{
public int Id { get; set; }
public string Title { get; set; }
public DateTime? Start { get; set; }
public DateTime? End { get; set; }
public bool isClosed { get; set; }
public bool isDeleted { get; set; }
public byte priorityLevel { get; set; }
public bool hasTimeLimit { get; set; }
public Customer customer { get; set; }
public int? customerId { get; set; }
public List<Note> Notes { get; set; }
public List<AttachmentFile> Attachments { get; set; }
public List<userTask> UserTasks {get; set;}
public int? userLastEditId { get; set; }
[ForeignKey("userLastEditId")]
public User userLastEdit { get; set; }
public DateTime? userLastEditDate { get; set; }
public DateTime taskCreatedDate { get; set; }
}
看起来像copyTaskSchedule。Id是主键或外键。您正在将值初始化为copyTaskSchedule。Id = 0;
我认为你必须修改这段代码
copyUserTask.TaskScheduleId = copyTaskSchedule.Id;
copyUserTask.TaskSchedule = copyTaskSchedule;
我删除了下面的代码
copyTaskSchedule = taskSchedule;
然后用下面的代码替换它。我手动将taskSchedule中的每个字段添加到copyTaskSchedule
copyTaskSchedule.Title = taskSchedule.Title;
copyTaskSchedule.Start = taskSchedule.Start;
copyTaskSchedule.End = taskSchedule.End;
copyTaskSchedule.userLastEditId = taskSchedule.userLastEditId;
copyTaskSchedule.priorityLevel = taskSchedule.priorityLevel;
copyTaskSchedule.isClosed = taskSchedule.isClosed;
copyTaskSchedule.hasTimeLimit = taskSchedule.hasTimeLimit;
copyTaskSchedule.Attachments = taskSchedule.Attachments;
copyTaskSchedule.customerId = taskSchedule.customerId;
copyTaskSchedule.userLastEditDate = NowDateTime;
copyTaskSchedule.isDeleted = taskSchedule.isDeleted;
copyTaskSchedule.taskCreatedDate = NowDateTime;