'Lazy loading in EFCore loads all the data even if not accessed
I have been trying to use lazy loading in ASP.NET core 6, I have followed the documentation to do so. However, the behavior of the lazy loading is not the same as described in the docs
Lazy loading means that the related data is transparently loaded from the database when the navigation property is accessed. Here
builder.Services.AddDbContext<AppDbContext>(
options => options.UseLazyLoadingProxies()
.UseSqlServer(builder.Configuration.GetConnectionString("Default")));
Currently I have the following entities
public class Book
{
public long Id { get; set; }
public string Name { get; set; }
public long AuthorId { get; set; }
public virtual Author Author { get; set; }
}
public class Author
{
public long Id { get; set; }
public string Name { get; set; }
}
And I have this endpoint
[HttpGet]
public IEnumerable<Book> GetBooks()
{
var list = _appDbContext.Books.ToList();
return list;
}
And the resulted SQL quires are
SELECT [b].[Id], [b].[AuthorId], [b].[Name]
FROM [Books] AS [b]
SELECT [a].[Id], [a].[Name]
FROM [Author] AS [a]
WHERE [a].[Id] = @__p_0
So in the endpoint I am not accessing the property Author inside Book entity, then why ef core is loading data that I dont need it kink of like eager loading but with two queries.
Solution 1:[1]
After investigation I realized that AutoMapper was accessing the Author so that is why its always retrieving the Author data.
So, lazyloading in EFCore is not convenient currently.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Ahmad |