11

I've heard that you should disable the lazy loading feature of EF in web applications. (ASP.NET). Here and here, for starters.

Now I'm really confused here because I always thought that lazy loading should always be enabled because it prevents unnecessary data fetching from the database. So, now my question is: Is it generally a better idea to disable lazy loading in web apps in terms of performance. If yes, could you explain why?

2
  • 3
    I believe that lazy loading introduces one more query to DB, instead of just one. So you can load all the data in one query using Include(), for example. Also if you use same entities in your API controllers in output positions, serializer will always traverse the whole object to serialize it completely what, in order, will call lazy loading on that entity. Commented Jan 27, 2019 at 7:47
  • 1
    The examples aren't convincing at all. They show code that should never be lazy loading, period. Whether it's in a web app or in a stateful client, the n + 1 query pattern should always be avoided. Maybe your question isn't opinion-based. If you can show me a case where you absolutely need lazy loading then yes, you need lazy loading, no discussion. Until then the only answer is: it depends. I.e. opinion-based, or broad, or unclear, whatever, but not a good fit on Stack Overflow. Commented Jan 27, 2019 at 12:05

6 Answers 6

14
+25

Disabling lazy loading will prevent Select N+1 performance problems as well as recursive serialization bail-outs, however it replaces those with another artifact, null references.

When working with web applications I do not disable lazy loading, but rather I ensure that my controllers/APIs do not return entities, but rather they return ViewModels or DTOs. When you adopt using POCO classes to feed your views just the amount of data, and the structure they need, and use .Select() or Automapper's ProjectTo<TViewModel>() to populate them via deferred execution, you avoid the need to worry about lazy load, and introduce better overall performance and resource usage for your application. Technically, using this approach, lazy loading can be disabled, so it's not really an argument for or against disabling it but rather that the mere act of disabling lazy loading won't make your web application "better".

Adopting ViewModels offers a number of advantages:

  • Avoids lazy load calls or unexpected #null references.
  • Sends only the data needed by the view/consumer, and nothing more. (Less data over the wire, and less information for hackers with debugging views.)
  • Builds efficient, index-able queries to the database server.
  • Provides a place for computed columns that won't trip up EF.
  • Helps reduce security issues (unexpected entity modifications) on the trip back. (A view model cannot simply be re-attached and committed to DB by a lazy developer)

So for me, the issue with web applications isn't to lazy load or not, it's simply to avoid passing entities to the client. I see far, far too many "examples" out there where they pass entities around. I don't consider it a healthy pattern.

As an example, using a view model the first question is "What data does my view actually need?" So given a product and a product category, if I want to send a product entity, but I also need the product category name for instance we hit a nasty problem if our product category contains a collection of products, and each of those products has a category. When we pass our product to the serializer it's going to hit that cyclic reference and it's either going to bail out (leaving a reference or collection #null) or it is going to throw an exception. But working through the Select N+1 we would iterate over the Product properties, hit the ProductCategory reference, then "SELECT FROM ProductCategory WHERE ProductCategoryID = 3". Then as we iterate over that product category, we hit another reference, and that is another SELECT.... and so-forth down the chain.

By using a view model you limit the data you want to retrieve to just what the view needs. I create a Product View-model which outlines the fields I care about, irregardless of where the data comes from. If I want something like a product, it's name, and it's category name:

public class ProductViewModel
{
    public int ProductId { get; set; }
    public string ProductName { get; set; }
    public string CategoryName { get; set; }
}

then to load it:

var viewModel = context.Products
    .Where(x => x.ProductId == productId) 
    .Select(x => new ProductViewModel
    {
        ProductId = x.ProductId,
        ProductName = x.Name,
        CategoryName = x.Category.Name
    }).Single();

Done. No lazy loads or eager loads required. This produces a single query that returns a single record with just the 3 columns we need. (Rather than the entire Product record, and it's Product Category)

As requirements get more complex we can introduce a view model hierarchy, but we can continue to flatten down the related data based on what the view actually needs. In some cases it might mean selecting into an anonymous type then translating those results into view models where we need to use functions etc. that EF cannot translate down to SQL. The approach is a powerful and fast alternative to relying on loading entities, but requires attention at the start to understand what the end consumer (view/API) will need from the data.

9

In web apps you have a lot of concurrent requests from different users, each request is being handled pretty fast (at least it should be), so you want to reduce number of DB calls during each request, because each DB request happens via network. With Lazy loading, every time you using relational property, it makes another call to DB to load this related data to your entity collection. So during one http request you can make a lot of additional requests to DB in such way, what from the performance prospective really hurts your application. In normal scenarios when you initially fetching your data from DB you already would know what related data do you need, so you can use eager loading of related entities to load everything that you need in one request to DB to handle particular http request.

0
5

I had one legacy project. I was really surprised when I was checking in sql profile how many requests go to the database. It was about 180(!) for the home page! The home page has only two list with 20-30 items in each. So, you should understand N+1 requests very well. You should check carefully on code review it. For me, lazy loading gives a lot of problems. You never know how many requests go to the database when you use that feature.

5
  • Your argument makes sense, but what confuses me here is that let's say we have some product categories in our system, and with every HTTP request, we have to fetch all these categories from the database, if we have disabled the lazy loading, when we fetch a category, all of its related products would be fetched too, since we have to fetch all categories, we actually fetch all the products in our database! And it'll be worse if we have some related entities to products, such as its "Brand". So based on this approach, in fact, we're fetching the entire database for each request, is that OK?
    – Arad
    Commented Jan 28, 2019 at 9:41
  • If you fetch entire database for each request, it means that you need entire database for each request - which is strange. In general of course you would need to separate your repository methods which brings some complexity, for example instead of one fetching method GetUsers (with Lazy Loading on you can further download all related data) you will end up with something like GetUsersWithPurchases and GetUsersWithSettings and so on. So for each particular use case you would need separate fetching logic. You shouldn't use one method that loads everything for every use case. Commented Jan 28, 2019 at 9:54
  • @AmirArbabian No, I do not need the entire database for each request, I said my scenario, I think you've misunderstood it, I said imagine you have an entity that lives in the database, and for each request, you need to fetch it from the database, without lazy loading, when you fetch that entity from the database, you're actually fetching all its related entities, and the related entities of each related entity again, and eventually you end up with the entire database in the memory. I hope I made myself clear...
    – Arad
    Commented Jan 28, 2019 at 10:58
  • @AmirHosseinAhmadi but if you need this entity with all it's relations that means you anyway will load all of that, but doing that via Lazy Loading you will do few request to database instead of one. Commented Jan 28, 2019 at 15:47
  • @AmirHosseinAhmadi, I use T-SQL. Every junior developer can write SQL requests. Or I can teach it for a couple of weeks. It is simpler. Everybody understands what's going on. I have two approaches. If a SQL request is without joins, I use ORM. Or if need to insert a big complex entity, I use ORM. This case is easier to use ORM. But I prefer SQL if I need complex SQL request with one or many joins.
    – Dmitresky
    Commented Jan 28, 2019 at 18:26
3

Lazy loading will create N+1 issue.

What does it mean?

It means that it will hit the DB once (at least) for each object loaded + the initial query.

Why is it bad?

Suppose you have these classes Movie and MovieGenre, and you have 100 movies with 30 genres between them in the DB

public class Movie
    {
        public int Id { get; set; }

        public string Name { get; set; }

        public virtual MovieGenre MovieGenre { get; set; }

        public byte MovieGenreId { get; set; }
}

public class MovieGenre
    {
        public byte Id { get; set; }

        public string Name { get; set; }
    }

Now suppose you are navigating to a page that will show all the 100 movies (remember the 30 movie genres?), the db will execute 31 queries (30 for each movie genre + 1 for movies) and the queries will be something like this

Initial query (+1 part):

SELECT Id, Name, MovieGenreId
From Movie

Additional queries (N part):

-- 1
SELECT Id, Name
From MovieGenre
Where Id = 1

-- 2
SELECT Id, Name
From MovieGenre
Where Id = 2

-- 3
SELECT Id, Name
From MovieGenre
Where Id = 3

-- 4
SELECT Id, Name
From MovieGenre
Where Id = 4
.
.
.

Eager loading avoids all this mess and will use one query with the correct joins.

since you are using C# here is a tool called glimpse that you might want to use to understand the issue further.

3
  • I understand what you're saying. But the question I have here is that for example let's say I want to fetch the data of a single genre, and that genre has 10,000 related movies. With eager loading, if I fetch that single genre, all the data of its 10,000 movies are also fetched. Isn't that an issue?
    – Arad
    Commented Mar 16, 2019 at 10:57
  • if you fetch all the genres movies aren't fetched unless you specifically ask for it. why? because Movie class is referencing MovieGenre not the other way around
    – Hoshani
    Commented Mar 16, 2019 at 11:32
  • In my EF class in the MovieGenre class I have a public List<Movie> Movies { get; set; }. Isn't that fetched every time I fetch a genre?
    – Arad
    Commented Mar 17, 2019 at 7:27
1

I think you need to start by asking few questions, before choosing one and rejecting other way:

  1. How big is my data set and do I need related data immediately? (This again is specific to your need)
  2. As other people have already told about N+1 issue; however, this becomes important depending on size of your dataset.
  3. Will it be pragmatic to have a round-trip to server to fetch related data?
  4. Then there is need of data. Whether you want it realtime or cached version will do?

My contribution to all important inputs by others.

1

I would say that lazy loading will certainly help the user not to fetch the data when it's usage is really seldom.

Imaging you have Master => Details scenario in the web application and by the time you realized that users are not that much interested in details. ( You can analyze and audit requests initiated by Users ). There would be no need to load details for each master record upfront.

On the other hand, if details are main part to interact with, Just do the eager loading and fetch the whole Master => Detail for each.

Apart from lazy/eager loading, make sure following:

Always enable paging at server side and load the limited data/ Load the data on user request as they navigates page by page.

If there are read requests mostly, disable AutoTracking.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.