📜 ⬆️ ⬇️

asp.net: Entity Framework, one difference from LINQ to Sql

This article would like to open a cycle of articles on the Entity Framework. In the future, I plan to post the results of my experience in the process of using EF, but for now I will give a free presentation of an interesting article on the topic “What is the difference between LINQ to SQL and the Entity Framework”.

Compare two pieces of code, the first is written using LINQ to SQL:
L2SDataContext linqToSqlContext = new L2SDataContext ();

this .MyDataGrid1.DataSource = linqToSqlContext.Customers.First (). Orders;

this .MyDataGrid1.DataBind (); * This source code was highlighted with Source Code Highlighter .

As a result of this code, three entries appear in the DataGrid.
The following code is written using EntityFramework:
EFEntities entityFrameworkContext = new EFEntities ();
')
this .MyDataGrid2.DataSource = entityFrameworkContext.Customers.First (). Orders;

this .MyDataGrid2.DataBind (); * This source code was highlighted with Source Code Highlighter .

As you can see, the code is almost the same in structure. But at the same time, not a single record is displayed in the DataGrid. What is the matter?

Lazy Loading


Lazy Loading (Lazy Loading) is exactly the technique available in Linq to Sql that secretly loads in the first example for Customers related Orders entries. There is no lazy download in the Entity Framework. There is an explanation from the EF development team at this point: “When developing a large project for developers, it’s very important to clearly understand how they get access to resources, such as a database.” they are accessing certain resources, such as the database). In other words, EF invites developers to determine for themselves what and when to load from the database. And this is done like this:
this .MyDataGrid2.DataSource = entityFrameworkContext.Customers
.Include ( "Orders" ) .First (). Orders; * This source code was highlighted with Source Code Highlighter .

Another way is to explicitly load the data:
var customer = entityFrameworkContext.Customers.First ();

customer.Orders.Load ();

this .MyDataGrid2.DataSource = customer.Orders; * This source code was highlighted with Source Code Highlighter .


Lazy loading is certainly a useful thing and saves a lot of time, so the author of the article goes on to give a small example of how this technique can be “returned” to EF. The example is not the most popular, because it is based on editing the code generated automatically.

Lack of lazy loading is perhaps one of the main differences in EF. This is a very important point to keep in mind when switching from Linq to Sql.

The original article “Entity Framework and Lazy Loading” can be read here:
www.singingeels.com/Articles/Entity_Framework_and_Lazy_Loading.aspx

Source: https://habr.com/ru/post/25774/


All Articles