Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
711 views
in Technique[技术] by (71.8m points)

entity framework - Using EF Core ThenInclude() on Junction tables

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:

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 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).

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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.

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

For instance the EF6 include chain:

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

translates to EF Core:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...