我在为实体定义模型构建器时遇到问题,并在尝试为该实体设置当前值时抛出错误。下面导致问题的行是:
context.Entry(tEntity.TaskSchedule.ScheduleDaysAndTimes).CurrentValues.SetValues(selectedTask.TaskSchedule.ScheduleDaysAndTimes);
我抛出一个“实体类型 EntityCollection`1 不是当前上下文模型的一部分。”
这是我的设置:
public class TaskEntity
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public virtual int TaskId { get; set; }
public virtual TaskScheduleEntity TaskSchedule { get; set; }
}
public class TaskScheduleEntity
{
/*Foreign Key*/
public virtual int TaskId { get; set; }
public virtual TaskEntity TaskEntity { get; set; }
public virtual ICollection<ScheduleDayTimeEntity> ScheduleDaysAndTimes { get; set; }
public class ScheduleDayTimeEntity
{
public int TaskScheduleID { get; set; }
public virtual TaskScheduleEntity TaskScheduleEntity { get; set; }
public virtual ICollection<DateTime?> Times { get; set; }
}
modelBuilder.Entity<TaskEntity>()
.HasKey(k => k.TaskId)
.HasRequired(s => s.TaskSchedule)
.WithRequiredPrincipal(p => p.TaskEntity)
.WillCascadeOnDelete(true);
modelBuilder.Entity<TaskScheduleEntity>()
.HasKey(k => k.TaskId)
.HasMany(t => t.ScheduleDaysAndTimes)
.WithRequired(a => a.TaskScheduleEntity)
.WillCascadeOnDelete(false);
modelBuilder.Entity<ScheduleDayTimeEntity>()
.HasKey(k => k.TaskScheduleID);
public void SaveTasks()
{
using (var context = new AppContext())
{
var tEntity = context.Tasks.First(x => x.TaskId == selectedTask.TaskId);
context.Entry(tEntity).CurrentValues.SetValues(selectedTask);
context.Entry(tEntity.TaskSchedule).CurrentValues.SetValues(selectedTask.TaskSchedule);
context.Entry(tEntity.TaskSchedule.ScheduleDaysAndTimes).CurrentValues.SetValues(selectedTask.TaskSchedule.ScheduleDaysAndTimes); /* Error thrown here*/
context.SaveChanges();
}
}