Reputation: 626
Query from EF results a complex Entity that has few associated properties and some are null. When I call DB to get details of those associated complex objects, EF pumps data into my first collection, where previously data was null. And it causes a self-referencing issue when converting to JSON.
Say a student has many Courses and courses have instructors. And a course also has a list of students.
When I get courses of a student it gives me a collection of those student courses where student.Courses
is null. Now when I get a collection of all courses from DB. student.Courses
is now no more null. It has a list of courses.
I have 2 Questions
I am on dot-net core 3. And I have SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
in place.
I want to avoid EF from doing the following
Entity Framework Core will automatically fix-up navigation properties to any other entities that were previously loaded into the context instance. So even if you don't explicitly include the data for a navigation property, the property may still be populated if some or all of the related entities were previously loaded.Ref
Upvotes: 0
Views: 50
Reputation: 89386
How to control this behavior in a way that collection one is not updated.
Load your entities using No-tracking queries.
No tracking queries are useful when the results are used in a read-only scenario. They're quicker to execute because there's no need to set up the change tracking information. If you don't need to update the entities retrieved from the database, then a no-tracking query should be used. You can swap an individual query to be no-tracking.
var blogs = context.Blogs
.AsNoTracking()
.ToList();
You can also change the default tracking behavior at the context instance level:
context.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking;
var blogs = context.Blogs.ToList();
https://learn.microsoft.com/en-us/ef/core/querying/tracking
Upvotes: 1