实体框架代码优先 - 恢复相同类型的集合

时间:2012-04-19 20:25:13

标签: entity-framework

我正在使用Entity Framework Code First。我正在尝试创建的类包含两个集合(相同类型)。我在恢复各自的藏品时遇到了问题。

我的课程如下:

public class Destination
{   
    public int DestinationId { get; set; } 
    public string Name { get; set; } 
    public List<Lodging> Lodgings { get; set; }           
    public List<Lodging> Lodgings2 { get; set; }
}
public class Lodging
{  
    public int LodgingId { get; set; } 
    public string Name { get; set; } 
    public Destination Destination { get; set; }
}

我创建了一个新目的地,然后我重新打开(关闭和打开)数据库连接。当我检索目标时,我的集合(dest.Lodgings和dest.Lodgings2)为空。如何恢复各自的馆藏?如果我的班级只有一个特定类型的集合,我可以执行以下操作:

var lodgings = context.Lodgings.Where(l => l.Destination.DestinationId == destId).ToList();

我可以看到关系是在数据库模式(Destination_DestinationId1和Destination_DestinationId2)中维护的,但我似乎无法访问它们。 任何建议都将不胜感激。

1 个答案:

答案 0 :(得分:1)

除了使用Include(正如您所发现的)(在检索目的地的同时从db加载相关数据)之外,您还可以在事后检索住宿。因此,如果您查询目的地并然后您想要住宿,那是可能的。一种方法称为显式加载,您将使用Load方法。另一个是延迟加载,这需要以特定的方式设置您的类,只是Lodgings属性的提及将触发对数据库的调用以检索它们。

在Ef团队博客上有一篇很棒的博客文章,内容是关于使用DbContext加载相关数据的各种方法:http://blogs.msdn.com/b/adonet/archive/2011/01/31/using-dbcontext-in-ef-feature-ctp5-part-6-loading-related-entities.aspx

HTH

朱莉