在连接表上使用 EF Core ThenInclude() [英] Using EF Core ThenInclude() on Junction tables

查看:23
本文介绍了在连接表上使用 EF Core ThenInclude()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将我的 .NET Framework (EF6) 代码转移到 ASP.NET Core (EF Core),我偶然发现了这个问题.下面是一些示例代码:

I'm transfering my .NET Framework (EF6) code to ASP.NET Core (EF Core), and I stumbled upon this issue. Here is some example code:

在 EF6 中,我使用 Include() 和 Select() 进行急切加载:

In EF6 I use Include() and Select() for eager-loading:

return _context.Post
.Include(p => p.PostAuthor.Select(pa => pa.Author).Select(a => a.Interests))

PostAuthor 是一个连接表,还有一个连接表AuthorInterest",我不需要在 EF6 中涉及(选择直接转到 a.Interests).

PostAuthor is a junction table and there is also a Junction table "AuthorInterest" which I didn't need to involve in EF6 (Select goes straight to a.Interests).

无论如何,我可以看到在 EF7 中这是重新设计的,这意味着我现在应该使用 ThenInclude() 进行嵌套查询.不过……

Anyway, I can see that in EF7 this is reworked, meaning that I should use ThenInclude() for nested queries now. However...

return _context.Post
  .Include(p => p.PostAuthor)
    .ThenInclude(pa => pa.Select(pa2 => pa2.Author))
...etc

由于 Select() 语句,上述代码失败.https://docs.efproject.net/en/latest/上的文档querying/related-data.html 似乎表明我不需要它,我可以立即访问 Author,但是我在最后一个 lambda 显示中得到了一个 ICollection,所以我显然需要 Select().我在查询中进一步查看了多个联结表,但为了简单起见,我们只关注第一个.

The above code fails because of the Select() statement. The documentation on https://docs.efproject.net/en/latest/querying/related-data.html seems to suggest that I don't need it and I can access Author immediately, but I get an ICollection in the last lambda displayed, so I obviously need the Select(). I go through multiple junction tables further on in the query, but for simplicity's sake, let's just focus on the first one.

我该如何完成这项工作?

How do I make this work?

推荐答案

但是我在显示的最后一个 lambda 中得到了一个 ICollection,所以我显然需要 Select()

but I get an ICollection in the last lambda displayed, so I obviously need the Select()

不,你没有.EF Core Include/ThenInclude 完全取代了 EF6 中使用的 Select/SelectMany 的需要.它们都具有用于集合和引用类型导航属性的单独重载.如果您对集合使用重载,ThenInclude 对集合的类型元素 进行操作,因此最后总是以单个实体类型结束.

No, you don't. EF Core Include / ThenInclude totally replace the need of Select / SelectMany used in EF6. Both they have separate overloads for collection and reference type navigation properties. If you use the overload with collection, ThenInclude operates on the type of the collection element, so at the end you always end up with a single entity type.

在您的情况下,pa 应该解析为您的联结表元素类型,因此 Author 应该可以直接访问.

In your case, pa should resolve to your junction table element type, so Author should be directly accessible.

例如 EF6 包含链:

For instance the EF6 include chain:

.Include(p => p.PostAuthor.Select(pa => pa.Author).Select(a => a.Interests))

转换为 EF Core:

translates to EF Core:

.Include(p => p.PostAuthor).ThenInclude(pa => pa.Author).ThenInclude(a => a.Interests)

这篇关于在连接表上使用 EF Core ThenInclude()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆