实体框架模型构建器映射问题

时间:2012-09-05 13:23:17

标签: c# entity-framework

我无法为我的实体定义我的模型构建器,并在尝试设置该实体的当前值时抛出错误。引起问题的线路如下:

       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();

        }

    }

1 个答案:

答案 0 :(得分:2)

DbContext.Entry()期待一个实体,并且你给它一个ICollection<ScheduleDayTimeEntity>

您需要更新代码,以便遍历集合:

foreach (var scheduleDayTimeEntity in tEntity.TaskSchedule.ScheduleDaysAndTimes)
{
  context.Entry(scheduleDayTimeEntity).CurrentValues.SetValues(/* Correct Value goes here */ );

}