使用代码优先自动检索复杂类型的ICollection [英] Auto-retrieve ICollection of complex type with Code First

查看:109
本文介绍了使用代码优先自动检索复杂类型的ICollection的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

[在Entity Framework 5.0 RC中使用代码优先DbContext]

[ Using Code First DbContext with Entity Framework 5.0 RC ]

不确定发生了什么事

  • 单个Tracks已存储
  • 和单独的PlaybackEvents已存储
  • 但是当我执行var tracks = myDbContext.Tracks.ToList();
  • 时不会填充TrackICollection<PlaybackEvent>
  • 即使我保存了myDbContext.Tracks.Add(track); myDbContext.SaveChanges();,其中trackICollection<PlaybackEvents>中有几个PlaybackEvents
  • the individual Tracks are stored
  • and the individual PlaybackEvents are stored
  • but the ICollection<PlaybackEvent> of Track is not populated when I do var tracks = myDbContext.Tracks.ToList();
  • even though I saved with myDbContext.Tracks.Add(track); myDbContext.SaveChanges(); where track had a couple of PlaybackEvents in ICollection<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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆