Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The purpose of Include() in ASP.NET MVC + Entity Framework

In the controllers generated by Visual Studio, as well as the sample application (ContosoUniversity), the Index action always has something like

var departments = db.Departments.Include(d => d.Administrator);

What's the difference between that and

var departments = db.Departments;

First I suspected that the first one (with Include) enables the view to retrieve department.Administrator. But the second one (without Include) seems to be able to do that as well.

like image 877
Jim Avatar asked Sep 10 '11 08:09

Jim


People also ask

What is include in EF core?

The Entity Framework Core (EF) extension method Include provides us the ability to load additional data besides the entities we are querying for. For example: loading products along with their translations. var products = Context. Products .

How can add Entity Framework in ASP.NET MVC?

Right-click the Controllers folder in Solution Explorer, select Add, and then click New Scaffolded Item. In the Add Scaffold dialog box, select MVC 5 Controller with views, using Entity Framework, and then choose Add.

Why Entity Framework is used in MVC?

Entity Framework is an open-source ORM framework for . NET applications supported by Microsoft. It enables developers to work with data using objects of domain specific classes without focusing on the underlying database tables and columns where this data is stored.


1 Answers

In first case (with Include) when you write department.Administrator servers the object from memory that has been eagerly loaded due to Include method. In the second case, an sql statement will be executed to fetch the Administrator record from the db for each department object.

like image 70
Muhammad Adeel Zahid Avatar answered Oct 13 '22 11:10

Muhammad Adeel Zahid