Discussion on lazy-loading of navigation properties
Note:
- Issue #10509 has been created to track actual work on lazy-loading. The new issue is locked so that it can be subscribed to for updates on the implementation without noise.
- This issue has been re-purposed to be discussion about lazy-loading in EF Core. It will not (for the time being) be locked because it is important to us that we don’t shut down channels of communication with the community.
With regard to feedback, I think it is worth reiterating some comments made a few months ago. We read and consider all feedback (and try to make the right choices based on it) no matter how it is delivered; that is, whether it is provided politely and with respect or not. Yelling at us or others with different opinions at best makes you feel good and us/them feel bad. It doesn’t achieve anything concrete. We are doing our best to prioritize features and implement them in the best way we can. We really appreciate your feedback and it makes a big difference on shaping the product. We personally appreciate it more when feedback is delivered in a respectful way, but please don’t stop providing constructive feedback.
Original issue:
Hi,
i was wondering if I am the only one that thinks EF Core is useless without Lazy Loading? Or do I do something wrong? Lets just consider a simple scenario when a course provider cancels a course on a course booking plattform written in MVC.
The user calls courses/cancel/1. The action would get the course and call cancel method like here
Course course = context.Courses.SingleOrDefault(c => c.Id = 1);
course.Cancel();
The cancel method then needs to cancel each booking on the course so it would do something like this
foreach(Booking booking in this.Bookings)
{
booking.Cancel();
}
The booking in turn would refund the transaction
foreach(Transaction transaction in this.Transactions)
{
transaction.Refund();
}
So for this to work, lazy loading is needed?! (The solution would be to eager load all the data on the controllers action method. But I do not know what will be needed from the controller?)
I'd appreciate any information on that.
I think you can do something like the following to eagerly load everything.
Course course = context.Courses.Include(c => c.Bookings).ThenInclude(b => b.Transactions).SingleOrDefault(c => c.Id = 1);
Otherwise, I'm assuming EF 7 has a way of explicitly loading properties like the following. However, I just upgraded to EF 7 today and haven't done that before. I think they changed the API around some. I'm assuming there has to be an equivalent though.
https://msdn.microsoft.com/en-us/data/jj574232.aspx#explicit
Also, as far as I know this site is for submitting bug reports, not questions.
We will be implementing explicit loading, but it's not there yet. Lazy loading is still undecided... so feedback is good - thank you.
Also, as far as I know this site is for submitting bug reports, not questions.
I think this can be considered a feature request. Lazy loading is still on the list of things we are considering... but it looks like we don't have a dedicated issue tracking it, so we'll use this one.
+1 for lazy load
I'm not saying that Lazy Loading isn't important, but the example provided is not a good example of "why". Such logic should live in a business logic layer which would orchestrate all of the actions required to fulfil the transaction.
It should at least have explicit loading. EF 7 doesn’t even have that at this point. In the example given, you are forced to load data that you don’t need since it was nested collections. I guess that’s no worse than it would be with lazy loading. I think you could be more selective with explicit. I guess the only way to load properties is using Include() ThenInclude() at this point. I find it surprising that the release won’t even have explicit loading. I guess it will still be workable. Lazy loading can get you into a lot of trouble though if you don’t pay attention to what’s happening. It can cause performance problems.
Jon
It's not as tidy as proper explicit loading support, but you can run a second LINQ query to load related data (EF will fixup all the navigation properties for you).
Course course = context.Courses.SingleOrDefault(c => c.Id = 1);
// sometime later, load the related data
context.Bookings.Where(b => b.CourseId == course.CourseId).ToList();
I already thought about this approach. But the problem is, that I do not have access to the context inside a model. Or has this changed in EF Core? I would need a way to inject the context or some other scope into the model to have the same context.
@AndiRudi that is true... but that is also true of explicit loading since explicit loading is about calling an EF API to load data.
@rowanmiller is there a way to prevent that behavior?
Course course = context.Courses.SingleOrDefault(c => c.Id = 1);
// sometime later, load the related data
context.Bookings.Where(b => b.CourseId == course.CourseId).ToList();
E.g. Ask EF not to 'fix-up' the navigation properties automatically?
@dneimke sure, if you want to execute a query without all the change tracking, fixup to existing entities that are already tracked, etc., then you can use the AsNoTracking() method on the query.
Out of interest, what is the scenario where you don't want that to happen?
Running tests against an InMemoryProvider. I want to ensure that I can execute multiple test cases from a Single serviceProvider instance without having the results dirtied by side effects
@dneimke That would work. Possibly better to register the context as scoped and then have a scope per test? That way you get a clean context per test.
True. Another example is that I want to write a test console app. To begin with I want to Ensure my Db exists and to seed it with data:
// Called from Main
db.Database.EnsureDeleted();
db.Database.EnsureCreated();
void SeedData()
{
// Add some parent records using Add or AddRange
// Add some child records using Add or AddRange
}
RunQuery(); // see below
Then, after adding that data, I want to query my DbSet
var parent = db.Parent.SingleOrDefault(...);
How can I ensure that the Children won't be attached?
int? count = parent.Children?.Count; // should be null
I would downvote this if possible, lazy loading is a source of problem, and hides some db work. Explicit is better than implicit IMHO! I prefer EF Core never implement this.
@dneimke you should use a separate instance of your context for the seeding.
@ilmax I don't think that easying the writing of code has anything to do with hiding. If you understand lazy loading, you don't have issues. Let's just go into the example of @rowanmiller above.
Explicit:
Course course = context.Courses.SingleOrDefault(c => c.Id = 1);
//This translates more or less to SELECT * FROM COURSE WHERE Id = 1
// Sometime later, load the related data
context.Bookings.Where(b => b.CourseId == course.CourseId).ToList();
//This translates more or less to SELECT * FROM Bookings WHERE CourseId = ...
Lazy:
Course course = context.Courses.SingleOrDefault(c => c.Id = 1);
//This translates more or less to SELECT * FROM COURSE WHERE Id = 1
// Sometime later, load the related data
course.Bookings.ToList();
//This translates more or less to SELECT * FROM Bookings WHERE CourseId = ...
I can't see any difference here, but I see the following improvements
- The data context used by the second call automatically is the same than used by the first one. This is important for the Unit-Of-Work. In the explicit call a developer could even create another data context (ok, thats not directly true because correct injection would take care of this, but it feels better)
- I don't want to query for the context all the time. This is boilerplate code.
- It is easier to read and more ddd than.
I think a lot of people get burned by lazy loading. I can understand why some people don't like it. I think it's a nice feature to have, but, I can understand why people don't like it. Namely, because when you develop an app, you need to watch the SQL logs and make sure the ORM isn't kicking off a lot of N+1 queries and the like. I haven't seen much of that with EF, but, had issues with this with EclipseLink on another platform. As long as there is a way to get everything you need loaded in an efficient manner, then, I would probably be all right with not having lazy loading. The new way that EF loads collections looks cool to me. I'm hopeful that this is more efficient than N+1 queries.
@AndiRudi my opinion about lazy loading is different, here are my concerns
- it's not simplify but hiding (at least IMHO) because a non EF expert cannot see something EF related in
course.Bookings.ToList()and explicit is better than implicit. - Requires that your model matches some EF requirements (e.g. virtual navigation properties) and I prefer avoid.
- It's super easy to fall in the SELECT N+1 trap
@ilmax I see... but then we don't need the navigation properties (.Bookings) at all? Then I always have to query the database with context.Bookings to make sure I have the correct data and using .Bookings would always be kind of "I dont know whats in there"....
The only case it would make sense is when using .Include(). And .Include() only makes sense when you write everything in one method because you'll never know what data is needed later (exception you write everything in one method).
OK, you convinced me. I think lazy loading should be there as well. I'm surprised that even explicit loading isn't there. I think that tells you where EF 7 is. It is a rewrite and important features are still missing. EF is my preferred ORM for .NET, but, it has always lagged behind other ORMs such as NHibernate. Microsoft was late to the game to begin with. In some respects, they still aren't to the point where NHibernate was years ago (although in other respects they are ahead). Unfortunately, RedHat bought JBoss and they jettisoned NHibernate. Last time I checked, the new developers couldn't seem to even figure out how to put a link to the documentation on their website. So, I will stick with EF, even if it isn't perfect. I have a feeling we will be waiting for quite some time though before we see lazy loading.