
In Entity Framework Core, the
Include
method is used to load related entities along with the main entity being queried. It is a method that is called on a DbSet or IQueryable instance and is used to specify one or more navigation properties that should be included in the query result.When you use Include
method, it performs a join query with the specified navigation property, retrieves the related entities and includes them in the result set. This can help reduce the number of database round trips and improve query performance.
For example, consider the following entities in a database:
csharppublic class Order
{
public int Id { get; set; }
public string OrderNumber { get; set; }
public int CustomerId { get; set; }
public virtual Customer Customer { get; set; }
}
public class Customer
{
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<Order> Orders { get; set; }
}
To retrieve all orders with their corresponding customers, you can use the Include
method as follows:
csharpvar ordersWithCustomers = dbContext.Orders.Include(o => o.Customer);
This will result in a query that joins the Orders table with the Customers table and retrieves all orders with their corresponding customers.
You can also use Include
method to specify multiple levels of related entities. For example, to retrieve all orders with their corresponding customers and customer's addresses, you can use the following code:
csharpvar ordersWithCustomersAndAddresses = dbContext.Orders
.Include(o => o.Customer)
.ThenInclude(c => c.Address);
This will result in a query that joins the Orders table with the Customers table and then joins the Customers table with the Addresses table, and retrieves all orders with their corresponding customers and customer's addresses.
Overall, the Include
method is a powerful tool for loading related entities in Entity Framework Core and can help improve query performance by reducing the number of database round trips required to retrieve the required data.
Comments
Post a Comment