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

c# entity-framework-core many-to-many


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

3/14/2019 3:40:16 PM

Popular Answer

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.


3/16/2019 1:09:11 PM

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow