Closed robertlarkins closed 3 years ago
I think the IReadOnlyList<Enrollment> Enrollments
and _enrollements
properties are only loaded if the LazyLoading
option is enabled and in the GetById
method in StudentRepository
you need to load the Enrollments
collection.
To remove an enrollment you need to call the Remove method in _enrollements
.
They must also be correctly mapped to the ef core.
ah ok, that's got it, I do need this sort of line _context.Entry(student).Collection(x => x.Enrollments).Load();
to populate the backing field.
That's the issue with EF's implementation of lazy loading, and I described how to work around this issue in clip "Introducing a Collection Invariant" of the "Mapping Backing Fields". Let me know if that's what you were looking for.
@vkhorikov Finally got back to rewatching that clip, and yes, that was exactly what I needed. Pity I didn't recall that before posting the issue 🤦♂️
In the Student.Disenroll method, it directly accesses the
_enrollments
backing field, but in EF Core 3.1.4 when I try to access the backing field of an IReadOnlyList it doesn't trigger the loading of the data from the database. It appears I have to call the property rather than the backing field for this to happen. I assume this is a recent change in EF Core? So I'm wondering how theDisenroll
method should be modified so it can remove an item from the_enrollments
backing field without first accessing theEnrollments
property to cause EF Core to populate_enrollments
.Here's the same issue posted on StackOverflow (by somebody else): https://stackoverflow.com/questions/63388035/ef-core-3-1-navigation-property-doesnt-lazy-load-entities-when-calling-the-bac The provided answer (and comments) don't seem to match with your recommendations, so I'm hoping there is a better way.