【问题标题】:Eager loading with Include()使用 Include() 预加载
【发布时间】:2009-03-21 11:35:12
【问题描述】:

想象一下这种情况:

var locations = from Locations in this.LocationDataContext.Locations
                                      .Include("ChildLocations")                      
                where
                     (Locations.LocationType.ID == 3) 
                select
                     Locations;

此查询将加载类型 == 3 的所有位置以及所有相关的子位置,好的。但我想弄清楚的是如何过滤正在加载的子位置。如果位置有 300 万个子位置怎么办?

也许是这样的? (不起作用,因为 ChildLocations 是一组实体)

var locations = from Locations in this.LocationDataContext.Locations
                                      .Include("ChildLocations")                      
                where
                     (Locations.LocationType.ID == 3) &&
                     (Locations.ChildLocations.LocationType.ID == 2)
                select
                     Locations;

谢谢。

【问题讨论】:

    标签: entity-framework linq-to-entities


    【解决方案1】:

    实体框架永远不会实现部分完成的实例。换句话说,您不能仅用 一些 的 ChildLocations 实现 Location。这将是一个“不完整”的对象,实体框架不允许这样做。

    但是,有一些解决方法。如果您只需要来自 ChildLocations 而不是来自 Location 本身的信息,只需选择:

    from Locations in this.LocationDataContext.Locations
    where Locations.LocationType.ID == 3
    from ChildLocation in Locations 
    where ChildLocation.LocationType.ID == 2
    select ChildLocation;
    

    在这种情况下,由于我们只选择 ChildLocations,因此只选择其中的几个是可以的,因为它们可以完全实现。只有在具体化位置时,我们才需要所有个子节点。

    另一种解决方法是将部分位置信息具体化为匿名类型。这允许您获取有关位置信息和子位置的一些信息,而不会违反实例只能以其完整形式实现的规则。由于您实际上并没有具体化一个真实的位置,因此不需要具体化整个事物:

    from Locations in this.LocationDataContext.Locations
    where Locations.LocationType.ID == 3
    select new 
    {
        ID = Locations.ID,
        LocationType= Locations.LocationType
        ChildLocations = from ChildLocation in Locations 
                         where ChildLocation.LocationType.ID == 2
                         select ChildLocation
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-11-27
      • 2017-12-05
      • 1970-01-01
      • 2011-03-12
      • 1970-01-01
      • 2017-01-29
      • 1970-01-01
      相关资源
      最近更新 更多