How to replace Eager Loading by using Lazy loading ?
Lets say like this.I am having below kind of EF query with lot of Include keys .Performance wise This is very slow.
So how can I improve the performance of below code by using Lazy loading ?
from owner in Catalog.Owners
where owner.Key == ownerKey
from invoice in owner.Invoices
where invoice.Provider.Key == providerKey
where invoice.Id == id
select invoice)
.Include(i => i.Owner.Credits)
.Include(i => i.Provider)
.Include(i => i.Items.Select(s => s.Allocation.Service))
.Include(i => i.Items.Select(s => s.Allocation.Pet))
.FirstOrDefault();
If you can give me a sample code explanation it’s perfect.
With EF 4.1 and greater, you just need to make sure to define your code-first navigation properties (properties that link to other entities) as
virtual. Then, if you are inside aDbContext, the linked entity will only be queried from the database when it is actually used (lazy loaded).However, eager loading is used when you want all the data right away. There are usually good reasons for this. So, I would first say that if you don’t know why you are eager loading, then don’t do it. Make sure your properties that link entities are virtual and then get rid of the
.Includestatements in your query.However, if you are taking the data you are querying outside of a
DbContextor you use the data right away it makes sense to pull that data into memory for the duration of your operation.So, in response to your question, it is not always a case of just replacing
eagerloading withlazyloading. You must look at what is being done with the data once it is queried and see how to only return the minimum set you need.Added example: