Entity Framework Core - 为集合包含多个级别的属性

eat*_*ate 2 c# entity-framework-core

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

我的情况的一个例子:

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

public class B
{
    public C c ...
}
Run Code Online (Sandbox Code Playgroud)

Entity Framework - Include Multiple Levels of Properties for EF Core 中提供的答案不包括嵌套属性是集合的情况,当我尝试时:

var wtv = Context.AItems.Include(a => a.listB).ThenInclude(b => b. )
Run Code Online (Sandbox Code Playgroud)

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

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

Ali*_*son 7

有两种重载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;
Run Code Online (Sandbox Code Playgroud)

您应该可以像这样使用它:

Context.AItems.Include(a => a.listB).ThenInclude(b => b.c)
Run Code Online (Sandbox Code Playgroud)

来自微软文档

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