使用导航加载实体2级深度

时间:2015-09-05 10:57:34

标签: c# linq entity-framework linq-to-entities navigation-properties

我有一个班级

public class Level1
{
   public int Id {get; set;}
   public virtual List<Level2> Level2List {get; set;}
}

public class Level2
{
   public int Id {get; set;}
   public int Level3Id {get; set;}
   public virtual Level3 Level3 {get; set;}
}

public class Level3
{
   public int Id {get; set;}
   public string Name {get; set;}
}

使用导航属性我可以像这样加载List<Level2>

var myList = _myLevel1Repository.GetSingle(x=>x.Id == Level1Id, x=>x.Level2List);

但是如何加载与Level2链接的Level3及其属性?

PS:无法进行延迟加载。  这是Getsingle函数

    public T GetSingle(Func<T, bool> where, params Expression<Func<T, object>>[] navProps)
    {
        T item = null;
        using (var context = new MyDbContext())
            item = GetFilteredSet(context, navProps).AsNoTracking().FirstOrDefault(where);
        return item;
    }

2 个答案:

答案 0 :(得分:1)

您的GetSingle方法应该是这样的:

public T GetSingle(Func<T, bool> where, params Expression<Func<T, object>>[] navProps)
{
    T item = null;
    using (var context = new MyDbContext())
    {
        IQueryable<T> query = context.Set<T>();

        //Include the navigations properties as part of the query
        if (navProps!= null)
        {
            query = navProps.Aggregate(query, (current, include) => current.Include(include));
        }
        item = query.Where(where).FirstOrDefault();
    }
    return item;
}

我不知道你在GetFilteredSet方法中做了什么,但我想你可以在方便的时候重新组织我上面展示的代码。包含多个导航级别的关键。 EF中的属性使用Include方法。当您使用此方法时,您将加载导航。属性作为查询的一部分(请查看此link中的预先加载部分)。现在,有两种Include方法:

  • DbQuery.Include Method

    使用此方法,您需要传递导航的路径。要作为字符串加载的属性,例如,在您的情况下,它将是:

    context.Set<Level1>.Include("Level2List.Level3");
    
  • DbExtensions.Include extension method

    这是我在上面的代码中使用的方法,您可以使用lambda表达式指定要包含的相关对象。恕我直言这是最好的变种,因为是强类型,如果你改变一些导航。您的实体中的属性名称,您也将收到编译错误。在上面分享的link中,您可以看到可用于包含不同级别导航的所有模式。属性。

    context.Set<Level1>.Include(l1=>l1.Level2List.Select(l2=>l2.Level3));
    

回到最初的问题,现在您可以使用GetSingle方法以这种方式包含多个级别:

var entity= _myLevel1Repository.GetSingle(x=>x.Id == Level1Id, x=>x.Level2List.Select(l2=>l2.Level3));

答案 1 :(得分:0)

如何使用include?

 var mylevel1s = _db.Level1(x=>x.Id == Level1Id).Include(x=> x.Level2List.Select(a=>a.Level3));