使用代码优先自动检索复杂类型的ICollection [英] Auto-retrieve ICollection of complex type with Code First
问题描述
[在Entity Framework 5.0 RC中使用代码优先DbContext]
[ Using Code First DbContext with Entity Framework 5.0 RC ]
不确定发生了什么事
- 单个
Tracks
已存储 - 和单独的
PlaybackEvents
已存储 - 但是当我执行
var tracks = myDbContext.Tracks.ToList();
时不会填充 - 即使我保存了
myDbContext.Tracks.Add(track); myDbContext.SaveChanges();
,其中track
在ICollection<PlaybackEvents>
中有几个PlaybackEvents
Track
的ICollection<PlaybackEvent>
- the individual
Tracks
are stored - and the individual
PlaybackEvents
are stored - but the
ICollection<PlaybackEvent>
ofTrack
is not populated when I dovar tracks = myDbContext.Tracks.ToList();
- even though I saved with
myDbContext.Tracks.Add(track); myDbContext.SaveChanges();
wheretrack
had a couple ofPlaybackEvents
inICollection<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; }
}
}
简化的PlaybackEvent
public class PlaybackEvent {
public string Id {get; set;}
public string Track_Id { get; set; }
}
推荐答案
您的ICollection
,即您的导航属性,需要声明为virtual
.
Your ICollection
, which is your navigation property needs to be declared as virtual
.
您的代码的另一建议是不要为导航属性明确声明您的getter和setter,而是将setter的责任移交给构造函数.使代码看起来像这样:
An additional suggestion to your code would be not to explicitly declare your getters and setters for your navigation property, but to move the setter responsibility to the constructor. Making your code look like this:
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
实体还需要一个导航属性,以启用一个到很多 PlaybackEvents关系的跟踪:
Your PlaybackEvent
entity also needs a navigation property to enable the one Track to many PlaybackEvents relationship:
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; }
}
这篇关于使用代码优先自动检索复杂类型的ICollection的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!