Lazy Loading and N+1 Query Problem in Entity framework Core

n+1 query problem in entit framework core

šŸ’»Source code

Lazy loading

You load related entities on demand rather loading at once. This approach is usually useful when you want to load related entities on a certain condition (otherwise always use eager loading).

To enable lazy loading, you need to install this package: Microsoft.EntityFrameworkCore.Proxies

And do following changes in Program.cs

builder.Services.AddDbContext<AppDbContext>(o=>o.UseLazyLoadingProxies()
.UseSqlite("Data Source = mydb.db"));

Look at the example below:

app.MapGet("/", async (AppDbContext context) => {
    foreach (var genre in await context.Genres.ToListAsync()) 
    {
        foreach (var book in genre.Books)
        {
            Console.WriteLine($"===> genre: {genre.Name}, Book: {book.Title}, Price : {book.Author}");
        }
    }
    return Results.Ok("Ok");
});

We are not loading books with genres at once. Rather we are loading books for each genres. Let’s take a look at logs of console.

[Read More]

Database Firsts Approach In EF Core

Database first approach with DotNet Core

I have used database first approach in theĀ .NET Framework 4.X. But It is the first time I am trying to use Db First approach in theĀ .NET Core (I am usingĀ .net 9). Microsoft refers it ‘Scaffolding (Reverse Engineering)’. Personally I prefer Dapper for DB First approach. May be you have an existing database and you want to use it with ENTITY FRAMEWORK, then this approach might be helpful. I am playing around it and documenting it and sharing that journey with you. Let’s see what it offers.

[Read More]