You Won't Believe The Hidden Dangers Of Lazy Loading
The REST Client VS Code extension sends REST and GraphQL requests from `.http` or `.rest` files with support for headers, bodies, variables, authentication, and request conversion.
Transcript 1 topic
Avoiding N plus one
0:00Don't screw this up. Lazy loading in EF Core is exactly what its name implies. It loads the data when you need it and not upfront. That sounds great. Right?
But it can lead to some real problems. Let's look at this sample code. It looks innocent enough, but if we look at EF Core statement logging, what in the world is going on? Why are we hitting the database so frequently? With lazy loading, we're only getting each blog's posts as we iterate through that for each.
That means every time we hit that blog dot post, it's making a call to the database to get just the post for that blog. You can see where this would cause a lot of inadvertent n plus one issues. So what should we do instead? One option is the include operator, which tells EF Core to include the post when you retrieve the blog. Well, looking at that code, we can see we're only using the URL of the blog.
So a more efficient way would be to return a dynamic object with only what we need, something like this. Well, that's all we'll do from now on. Well, maybe not. Be sure to check that video below to see some other issues you might get into using the include operator.
Sign in to join in. Reading needs nothing.