asp.net: Entity Framework, one of the differences from LINQ to Sql

    With this article I would like to open a series 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 “How LINQ to SQL differs from 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 records will 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 here?

    Lazy Loading


    Lazy Loading is just that technique available in Linq to Sql that covertly loads related Orders records in the first example for Customers. There is no lazy loading in the Entity Framework. There is an explanation from the EF development team for this point: “When architecting a larger project, it is highly important for developers to clearly understand when they are accessing certain resources, such as the database). In other words, EF invites developers to determine for themselves what and when to download 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, therefore the author of the article gives a small example of how this technique can be “returned” to EF. The example is not the most demanded, because it is based on editing the code generated automatically.

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

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

    Also popular now: