Entity Framework Core - 包含集合属性的多层级

3
我希望了解如何在Entity Framework Core中为集合包含多个级别的属性。以下是我的情况示例:
public class A
{
    public ICollection<B> listB ...
}

public class B
{
    public C c ...
}

Entity Framework - Include Multiple Levels of Properties中所提供的答案并没有涵盖嵌套属性为集合的情况,例如:

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

我只能访问ICollection本身(listB)的属性,无法访问其中包含的B对象的属性,因此我无法在其中包含C对象。
我设法通过手动方式完成此操作(比我希望的要冗长得多),分别加载B对象并将所需内容包含在其中,然后才将它们添加到A的listB中。但是,在我的实际情况中,我想要包含在下一级的属性也是集合,因此这变得越来越不实用。有没有更简单、更优雅的方法呢?
1个回答

9

有两种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方法后跟随一个集合导航属性时,可能会导致正确的表达式被标记为语法错误。这是IntelliSense bug的症状,该bug已在https://github.com/dotnet/roslyn/issues/8237上得到追踪。只要代码是正确的并且可以成功编译,就可以安全地忽略这些虚假的语法错误。


@DiegoTorres 谢谢你指出这一点,我已经将它添加到我的答案中了。 - Alisson Reinaldo Silva

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接