【问题标题】:How to include navigation properties eagerly for child objects如何为子对象急切地包含导航属性
【发布时间】:2013-07-11 12:03:22
【问题描述】:

假设我的对象图看起来像:

User
 => Friends
   => Clicks
     => Urls

所以当我加载一个用户时,我也想快速加载导航属性 Friends。我希望朋友对象能够快速加载 Clicks 等等。

使用我现在拥有的代码,我只能为 1 级执行此操作:

public User GetUserById(int userId)
{
  return Get(x => x.Id == userId, includeProperties: "Friends").FirstOrDeafult();
}

这可能吗?

【问题讨论】:

    标签: c# entity-framework-4.1 repository-pattern


    【解决方案1】:

    显然这个存储库实现只是用逗号(includeProperties.Split(new char[] { ',' })分割includeProperties参数,然后调用

    query = query.Include(includeProperty);
    

    对于拆分的结果数组中的每个元素。对于您的示例,您可以使用虚线路径:

    return Get(x => x.Id == userId, includeProperties: "Friends.Clicks.Urls")
        .FirstOrDefault();
    

    它将加载从根User 实体到最后一个导航属性Urls 的路径上的所有实体。

    如果您在 User 中有另一个导航属性 - 比如说 Profile - 并且您也想急切地加载它,那么似乎支持此语法:

    return Get(x => x.Id == userId, includeProperties: "Profile,Friends.Clicks.Urls")
        .FirstOrDefault();
    

    【讨论】:

    猜你喜欢
    • 2016-05-28
    • 1970-01-01
    • 2011-06-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多