LeftJoin and RightJoin in Ef Core 10

LeftJoin and RightJoin in  Ef Core 10

Previously there was no simple solution for left or right join. We had to use DefaultIfEmpty or GroupJoin and SelectMany.

With DefaultIfEmpty():

var customerOrders = await (
    from c in ctx.Customers
    join o in ctx.Orders on c.CustomerId equals o.CustomerId into orders
    from o in orders.DefaultIfEmpty()
    select new {
        c.CustomerId,
        c.CustomerName,
        OrderId = o == null ? 0 : o.OrderId
    }
).ToListAsync();

I have used the way described above in most of my career. It was really hard to remember that syntax and I always struggled with that.

[Read More]

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

Lazy Loading and N+1 Query Problem in Entity 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 Firsts Approach In EF 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]