0

[将 Code First DbContext 与 Entity Framework 5.0 RC 一起使用]

不确定发生了什么?

  • 个人Tracks被存储
  • 并且个人PlaybackEvents被存储
  • 但是当我这样做时没有填充ICollection<PlaybackEvent>ofTrackvar tracks = myDbContext.Tracks.ToList();
  • 即使我保存了其中myDbContext.Tracks.Add(track); myDbContext.SaveChanges();track几个PlaybackEventsICollection<PlaybackEvents>

希望轨道的相关部分

public class Track 
{
    public string Id {get; set;}

    private ICollection<PlaybackEvent> _playbackEvents;

    public ICollection<PlaybackEvent> PlaybackEvents
    {
        get { return _playbackEvents ?? (_playbackEvents = new List<PlaybackEvent>()); }
        set { _playbackEvents = value; }
    }
}

简化的播放事件

public class PlaybackEvent {
    public string Id {get; set;}

    public string Track_Id { get; set; }
}
4

1 回答 1

1

您的ICollection,这是您的导航属性,需要声明为virtual.

对您的代码的另一个建议是不要为您的导航属性显式声明您的 getter 和 setter,而是将 setter 职责移至构造函数。使您的代码如下所示:

public class Track  
{ 
    public Track()
    {
        this.PlaybackEvents = new HashSet<PlaybackEvent>();
    }

    // Primary key
    public string Id {get; set;} 

    // Navigation property
    public virtual ICollection<PlaybackEvent> PlaybackEvents { get; private set; } 
 }

您的PlaybackEvent实体还需要一个导航属性来启用一个Track 到多个PlaybackEvents 关系:

public class PlaybackEvent 
{  
    // Primary key
    public string Id {get; set;}  

    // Foreign key
    public string Track_Id { get; set; }  

    // Navigation property
    public virtual Track Track { get; set; }
}  
于 2012-07-11T06:57:03.857 回答