Updated May 18, 2023
Introduction to LINQ Include
LINQ include helps out to include the related entities which loaded from the database. It allows retrieving the similar entities to be read from database in a same query. LINQ Include(), which points towards similar entities, must read from the database to get in a single query.
Syntax:
Let’s understand the following syntax,
var C_OrderDetails=context.customer details.Include ("OrderDetails").ToList();
In this syntax, we use the include method to combine the related entities in the same query, like merging multiple entities in a single query.
How does include work in LINQ?
LINQ Include(), which point towards the similar entities that must read from the database to get in a single query. Let’s understand the below example, like how the LINQ Include functionality loads the related entities automatically. To assume that the CustomerDetails Object has links to its OrderDetails and those orders have a reference of LineItems, those LineItems also had a reference to the ProductDetails; by using LINQ Include(), it allows you to specify the related entities to be read from the database in a single query.
Var COrderDetails=context.CustomerDetails.Include ("OrderDetails").ToList();
By using only SQL statements instead of using the Include() methods, we need to generate the following queries to retrieve the same above,
SELECT * FROM CustomerDetails;
Instead of using Include (“OrderDetails”), the code looks as follows,
SELECT * FROM CustomerDetails
JOIN OrderDetails
ON Customer_ID=OrderDetails.Customer_ID;
In the same single query, we can read all related entities from the database; in the case of using Include(), if we want to include the ProductDetails and LineItems also in the same query, it looks like as