实体框架核心-为集合包括属性的多个级别

时间:2018-10-26 03:40:45

标签: c# entity-framework-core

我想知道如何在Entity Framework Core中为集合包含多个级别的属性。

我的情况的一个例子:

SELECT Groups.id AS `Groups__id`, Groups.name AS `Groups__name`, Groups.created AS `Groups__created`, Groups.modified AS `Groups__modified`, (SELECT (COUNT(*)) FROM positions Positions WHERE Positions.group_id = Groups.id) AS `count` FROM groups Groups

当我尝试时,Entity Framework - Include Multiple Levels of Properties中针对EF Core的答案未涵盖嵌套属性为集合的情况:

public class A
{
    public ICollection<B> listB ...
}

public class B
{
    public C c ...
}

我只能访问ICollection本身的属性(listB),而不能访问其中包含的B对象的属性,因此我可以在其中包含C对象。

我设法手动执行此操作(比我希望的要冗长得多),分别加载B对象并包括我想要的内容,然后才将它们添加到A的listB中。但是,在我的现实生活中,我想在以下级别中包含的属性也适用于集合,因此这变得越来越不实用。有没有更简单,更优雅的方法?

1 个答案:

答案 0 :(得分:2)

ThenInclude有两个重载,一个用于上一个导航属性是单个实体的情况,另一个用于集合:

public static IIncludableQueryable<TEntity, TProperty> ThenInclude<TEntity, TPreviousProperty, TProperty>([NotNullAttribute] this IIncludableQueryable<TEntity, TPreviousProperty> source, [NotNullAttribute] Expression<Func<TPreviousProperty, TProperty>> navigationPropertyPath) where TEntity : class;

public static IIncludableQueryable<TEntity, TProperty> ThenInclude<TEntity, TPreviousProperty, TProperty>([NotNullAttribute] this IIncludableQueryable<TEntity, IEnumerable<TPreviousProperty>> source, [NotNullAttribute] Expression<Func<TPreviousProperty, TProperty>> navigationPropertyPath) where TEntity : class;

您应该能够像这样使用它:

Context.AItems.Include(a => a.listB).ThenInclude(b => b.c)

来自Microsoft Docs

  

当前版本的Visual Studio提供了不正确的代码完成选项,当在集合导航属性之后使用thenInclude方法时,可能导致正确的表达式被标记为语法错误。这是在https://github.com/dotnet/roslyn/issues/8237处跟踪的IntelliSense错误的症状。只要代码正确且可以成功编译,就可以忽略这些虚假的语法错误。