vkhorikov / DddAndEFCore

Source code for the DDD and EF Core Pluralsight course
https://enterprisecraftsmanship.com/ps-ef-core
MIT License
249 stars 90 forks source link

EF Core backing field not returning data from database #3

Closed robertlarkins closed 3 years ago

robertlarkins commented 3 years ago

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 the Disenroll method should be modified so it can remove an item from the _enrollments backing field without first accessing the Enrollments 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.

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

robertlarkins commented 3 years ago

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.

vkhorikov commented 3 years ago

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.

robertlarkins commented 3 years ago

@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 🤦‍♂️