简体   繁体   中英

C# Core 2.1 EF many-to-many relationship querying

I am having an issue with many-to-many join tables in C# Core EF. I'm converting .NET Framework code to .NET Core 2.1 and it's a bit trickier as those join tables must be manually defined in the dbcontext with an accompanying model class instead of being handled in the background as before.

I can't figure out how to do the querying. Eager loading.

For example, I used to just include the related data using

db.Student.Include(x => x.Course).Where(...

Now that doesn't work anymore as I can only load the join-table data

db.Student.Include(x => x.CourseStudent).Where(...

If I do

db.Student.Include(x => x.CourseStudent).ThenInclude(y => y.Course).Where(...

then I get the error:

The Include property lambda expression 'x => {from CourseStudent y in x.Course select [y].Course}' is invalid. The expression should represent a property access: 't => t.MyProperty'. To target navigations declared on derived types, specify an explicitly typed lambda parameter of the target type, E.g. '(Derived d) => d.MyProperty'. For more information on including related data, see http://go.microsoft.com/fwlink/?LinkID=746393.

I've read that page and can't anything useful there. It says .ThenInclude() should work but it doesn't.

Student is derived from Person but all the members that matter are in Student. Course is just Course.

Something's wrong and I don't know what....

When designing a small example project I stumbled upon the solution. It was the IntelliSense bug that tricked me, even though I had read about it.... So problem solved.

https://docs.microsoft.com/en-us/ef/core/querying/related-data#including-multiple-levels

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM