Entity Framework Include method

Include method in Entity Framework has two overloads. One of which takes navigation property as a string. The other one is Include lambda method. The Include Lambda method is an extension method from the namespace System.Data.Entity. In this tutorial, we look at include method, and learn how to load entities from multiple levels and multiple tables.

The sample database for this example is taken from the AdventureWorks database. Download it and use it to create the model. You can refer to the article code first existing database to reverse engineer the model. Also, you look at the SQL queries that EF generates by logging them to console

Include method

The following example shows how to use the include method against a reference property ProductModel. The EF creates a join statement for each include method and sends it database. Thus retrieving List of Products and its ProductModel in a single query.


Best Entity Framework Books
The Best Entity Freamework Books, which helps you to get started with Entity Framework  

Corresponding SQL

Include a Collection Property

The Products is collection navigation property for the ProductModel.

Filter the child collection

The Include does not allow us to filter the child collection

Include from Multiple Tables

In the following example we have three tables in the include method. Note that all are reference properties.

Include method Multiple Levels

You can also load entities to multiple levels using the following syntax. The include statement includes bothEmployee and Person table (note that both are reference types). The Query will use join to bring data from both the tables as shown below

Summary

In this article, we showed how to make use of the Include method in Entity Framework. The Include Lambda method is an extension method from the namespace System.Data.Entity. Using it we can eagerly load the related entities in a Single Query. We also learned how to load entities from multiple levels and multiple tables.

Leave a Comment

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top