2017-07-14 145 views
1

我有一個我正在創建的YogaSpaceEvent,其中有一個名爲RegisteredStudents的實體。當我創建YogaSpaceEvent時,我想在保存之前向其添加RegisteredStudent實體。但是當我說 'newEvent.RegisteredStudents.Add(newStudent);'我得到的對象引用未設置爲對象的實例。有沒有我忽略的東西,或者我必須添加一個事件到數據庫,因爲我可以將註冊的學生添加到該newEvent行?嘗試在實體框架中填充子實體的異常

YogaSpaceEvent newEvent = new YogaSpaceEvent 
      { 
       EventDateTime = details.EventDate.AddHours(DateTime.Parse(displayedTime).Hour).AddMinutes(DateTime.Parse(displayedTime).Minute), 

       Time = details.StartTime, 
       Duration = details.Duration, 
       //blah blah blah 

       DateCreated = DateTime.Now, 
       DateUpdated = DateTime.Now 
      }; 

RegisteredStudent newStudent = new RegisteredStudent { StudentId = 12345 }; 
newEvent.RegisteredStudents.Add(newStudent); 

yogaSpace.YogaSpaceEvents.Add(newEvent); 

dbContext.SaveChanges(); 

這裏有兩個實體

public class YogaSpaceEvent 
{ 
    public YogaSpaceEvent() {} 

    [Key] 
    public int YogaSpaceEventId { get; set; } 

    [Index] 
    public int YogaSpaceRefId { get; set; } 

    [ForeignKey("YogaSpaceRefId")] 
    public virtual YogaSpace YogaSpace { get; set; } 

    [Required] 
    [Index] 
    public DateTime EventDateTime { get; set; } 

    [Required] 
    public YogaTime Time { get; set; } 

    [Required] 
    public YogaSpaceDuration Duration { get; set; } 

    public virtual ICollection<RegisteredStudent> RegisteredStudents { get; set; } 
} 

這裏是RegisteredStudent

public class RegisteredStudent 
{ 
    public RegisteredStudent() {} 

    [Key] 
    public int RegisteredStudentsId { get; set; } 

    [Index] 
    public int YogaSpaceEventRefId { get; set; } 

    [ForeignKey("YogaSpaceEventRefId")] 
    public virtual YogaSpaceEvent YogaSpaceEvent { get; set; } 

    public int StudentId { get; set; } 
} 

回答

1

調用Add之前實例化您的收藏RegisteredStudents

public YogaSpaceEvent() 
    { 
     this.RegisteredStudents = new List<RegisteredStudent>(); 
    }