在连接表上使用EF

在连接表上使用EF

本文介绍了在连接表上使用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.

我如何进行这项工作?

推荐答案

不,你不知道. EF Core Include/ThenInclude完全替代了EF6中使用的Select/SelectMany的需求.两者都有单独的集合和引用类型导航属性的重载.如果对集合使用重载,则ThenInclude将对集合 element 的类型进行操作,因此最后,您总是以单个实体类型结束.

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包含链:

.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()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 15:26