entity framework include in csharp

To include related entities in Entity Framework, we use the Include() method. The Include() method specifies the related objects that should be retrieved when querying the database.

Here's an example of how to use Include() with Entity Framework:

main.cs
using (var context = new MyDbContext())
{
    var orders = context.Orders
        .Include(o => o.Customer)
        .ToList();
}
129 chars
7 lines

This code retrieves all Order objects from the Orders table, and also includes the related Customer objects for each order.

The Include() method is part of LINQ, and can be used with any LINQ query that supports navigation properties. It can also be used with multiple related entities, as shown in this example:

main.cs
using (var context = new MyDbContext())
{
    var orders = context.Orders
        .Include(o => o.Customer)
        .Include(o => o.OrderItems)
            .ThenInclude(oi => oi.Product)
        .ToList();
}
208 chars
9 lines

This code retrieves all Order objects from the Orders table, and includes the related Customer objects as well as the OrderItems objects for each order. The ThenInclude() method is used to include the related Product objects for each OrderItem.

By using the Include() method, we can reduce the number of database queries required to retrieve related data, and improve the performance of our application.

gistlibby LogSnag