Working With Lazy Loading and Eager Loading in Entity Framework Core and Entity Developer

Entity Framework is an Object Relational Mapper (ORM) software from Microsoft that has been an especially widespread from the time it was obtainable. It allows builders to create data-centric purposes by programming towards a conceptual mannequin quite than the relational mannequin thereby fixing the impedance mismatch between the way in which information is represented within the utility and the way it’s truly saved within the database. Whereas Entity Framework runs on .NET Framework, Entity Framework Core can run on .NET Core surroundings.

Whereas Entity Framework runs on .NET Framework, Entity Framework Core can run on .NET Core surroundings.

This text presents a dialogue on how we will work with lazy loading utilizing EF Core and Entity Developer for information entry.

Conditions

To have the ability to work with the code examples demonstrated on this article, it is best to have the next put in in your system:

  • Visible Studio 2019 Neighborhood Version or increased
  • SQL Server 2019 Developer Version or increased
  • Entity Developer from Devart

You’ll be able to obtain Visible Studio 2019 from right here.

You’ll be able to obtain SQL Server 2019 Developer Version from right here.

You’ll be able to obtain a replica of Entity Developer (trial model) from right here.

Entity Developer: A Visible ORM Designer Device

We’ll reap the benefits of Entity Developer to generate the mannequin and corresponding courses. Entity Developer from Devart is a modeling and code era software that allows you to design your information entry layer visually and lets you turn into extra productive as a developer. You’ll be able to reap the benefits of Entity Developer to generate information entry layer code mechanically utilizing one unified interface – in consequence, possibilities of error creeping into your Information Entry code are minimal.

Entity Developer is built-in properly with Visible Studio upon set up and helps ADO.NET Entity Framework, Entity Framework Core, Hibernate, LinqConnect, Telerik Information Entry, and LINQ to SQL. You may get began utilizing Entity Developer after downloading a trial model from right here.

Creating the Database

First off, we have to have a database towards which the queries might be executed. For the sake of simplicity, we’ll reap the benefits of the Northwind database quite than creating our personal database. Should you don’t have the Northwind database obtainable, you will get the script(s) from right here.

Create a New ASP.NET Core Mission

Assuming that the mandatory software program has been put in in your laptop to have the ability to work with Entity Developer, comply with the steps outlined beneath to create a brand new ASP.NET Core Net API undertaking.

  1. First off, open the Visible Studio 2019 IDE
  2. Subsequent, click on “Create a brand new undertaking” as soon as the IDE has loaded
  3. Click on “Create a brand new undertaking”
  4. Subsequent, choose “ASP.NET Core Net Software”
  5. Click on the “Subsequent” button
  6. Specify the undertaking title and placement — the place it needs to be saved in your system
  7. Optionally, click on the “Place resolution and undertaking in the identical listing” checkbox.
  8. Subsequent, click on the “Create” button
  9. Within the “Create a brand new ASP.NET Core Net Software” dialog window that’s proven subsequent, choose “API” because the undertaking template.
  10. Choose ASP.NET Core 3.1 or later because the model.
  11. You must disable the “Configure for HTTPS” and “Allow Docker Assist” choices by disabling the respective checkboxes.
  12. Since we’ll not be utilizing authentication on this instance, specify authentication as “No Authentication”.
  13. Lastly, click on on the “Create” button to complete the method.

Create an Entity Information Mannequin

On this part, we’ll discover tips on how to create an Entity Information Mannequin utilizing Entity Developer. We’ll use each the 2 approaches database first and mannequin first. To create an Entity Information Mannequin utilizing Entity Developer in Visible Studio 2019, comply with the steps outlined beneath.

  1. Proper-click on the undertaking within the Resolution Explorer Window
  2. Choose Add -> New Merchandise as proven in Determine 1

 

Determine 1

  1. Within the “Entity Developer: Create Mannequin Wizard” window you may specify how the mannequin needs to be created. You’ll have two selections – Database First and Mannequin First
  2. Choose the Database First Strategy and click on on Subsequent to proceed.
  3. Within the subsequent display screen, specify the connection properties and click on on the “Subsequent” button to proceed.
  4. Specify how the mannequin needs to be generated within the subsequent display screen. Word that the “Generate from Database” possibility is chosen by default.
  5. Since we’ll want the mannequin to be created from the database, click on on the “Subsequent” button to proceed.
  6. Within the subsequent display screen the database metadata is retrieved by the Entity Developer runtime. Right here’s the place it is best to specify the database objects that needs to be part of your Entity Information Mannequin. Choose the tables right here as proven in Determine 2.

Determine 2

  1. Within the “Arrange naming guidelines” display screen you may specify naming guidelines in your entities.
  2. Click on on the “Subsequent” button to proceed.
  3. Within the subsequent display screen, specify the Context Namespace as and click on on the “Subsequent” button to proceed.
  4. Now you may specify what your mannequin diagram ought to include.
  5. Click on on the “Subsequent” button to proceed.
  6. Now you may select the code era templates if you wish to.
  7. Click on on the “Subsequent” button to proceed.

Determine 3

  1. Click on on the “Subsequent” button once more to proceed.
  2. Click on “End” to finish the method.

Your Entity Information Mannequin utilizing Entity Developer has been created. Right here’s how your Entity Information Mannequin would appear to be.

Determine 4

Keen Loading, Specific Loading, and Lazy Loading

You’ll be able to load related entities utilizing navigation properties in EF Core. Keen loading facilitates the loading of associated entities as a part of the unique question. In EF Core, it’s possible you’ll load related entities at a number of ranges by combining the Embody() and ThenInclude() extension strategies. You’ll be able to load associated entities in Entity Framework Core in one of many following methods:

  • Keen Loading – That is used to load associated entities as a part of the preliminary question. The associated information is loaded on the time when the question is executed utilizing the Embody() methodology.
  • Specific Loading – In Specific Loading, when a question returns information, the associated entities usually are not returned on the identical time. They’re solely loaded when explicitly requested by the applying utilizing the Load methodology on the navigation property.
  • Lazy Loading – That is used to load associated entities when the navigation property is accessed. That is the default phenomenon used for delayed loading of associated entities.

Working With Keen Loading

The next code snippet illustrates how you should use keen loading now.

var outcome = (from o in dataContext.Orders.Embody("OrderDetails") choose o);

You can too use LINQ methodology syntax to implement keen loading as properly. The next code snippet reveals how one can load associated entities utilizing Keen Loading in Entity Framework Core.

[HttpGet]

public IEnumerable<Order> Get()

  utilizing (NorthwindModel dataContext = new NorthwindModel())
  
    var outcome = (from o in dataContext.Orders.Embody("OrderDetails")
    the place o.ShipCity == "London" && o.OrderDetails.Choose
    (x => x.Low cost == 0).FirstOrDefault()
                              choose o);
    return outcome;
   

Loading A number of Ranges of Associated Entities

You’ll be able to reap the benefits of the ThenInclude() methodology to load a number of ranges of associated entities as properly. Here is an instance:

var information = dataContext.Orders.Embody(orders => orders.OrderDetails).ThenInclude(orders => orders.Product).ToList();

Here is one other instance – this one makes use of the AdventureWorks database.

utilizing (var context = new AdventureWorksContext())


    var information = context.Worker
       .Embody(j => j.JobCandidate)
       .ThenInclude(b => b.BusinessEntity)
       .ToList();

It’s also potential to chain a number of calls to the ThenInclude() extension methodology to load information in a number of ranges. The next code snippet reveals how a number of calls to the ThenInclude() extension methodology could be chained.

 var information = context.Buyer
    .Embody(d => d.SalesOrderHeader)
    .ThenInclude(p => p.SalesOrderDetail)
    .ThenInclude(t => t.SalesOrder)
    .ToList();

Working With Lazy Loading

Lazy loading is a sample that lets you defer the loading of information until the time it’s truly wanted. Whereas this would possibly offer you advantages in sure use instances, it might additionally degrade the applying’s efficiency in sure different use instances comparable to internet purposes. It needs to be famous that Entity Framework Core doesn’t help Lazy Loading out of the field – you should allow it explicitly. Lazy loading could be enabled utilizing one of many following methods:

  • Utilizing Proxies
  • Utilizing the ILazyLoader service

Utilizing Proxies

Set up the Microsoft.EntityFrameworkCore.Proxies bundle onto your undertaking utilizing the NuGet Package deal Supervisor. Subsequent, you may reap the benefits of the UseLazyLoadingProxies methodology to facilitate the creation of proxies within the OnConfiguring methodology of your DbContext as proven within the following code snippet:

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)

   //Different code
   optionsBuilder.UseLazyLoadingProxies();
   CustomizeConfiguration(ref optionsBuilder);
   base.OnConfiguring(optionsBuilder);

Lastly, it is best to be sure that the navigation properties are marked as digital. That is all you should do!

Utilizing the ILazyLoader Interface

You’ll be able to leverage the ILazyLoader interface to lazy load the navigation properties. To have the ability to use this method, it is best to set up the Microsoft.EntityFrameworkCore.Abstractions bundle onto your undertaking. Subsequent, it is best to reference the Microsoft.EntityFrameworkCore.Infrastructure meeting in your program to have the ability to use the ILazyLoader interface.

Your entity class ought to have two constructors – one which accepts a reference to the ILazyLoader interface as a parameter and the opposite is a default constructor. The next code snippet illustrates how lazy loading could be carried out utilizing the ILazyLoader interface.

    

utilizing Microsoft.EntityFrameworkCore.Infrastructure;
public class Order

non-public readonly ILazyLoader _lazyLoader;

public Order()




public Order(ILazyLoader lazyLoader)


   _lazyLoader = lazyLoader;



non-public Checklist<Buyer> _customers;
public int OrderID  get; set; 
public Checklist<Buyer> Clients
 
            get => _lazyLoader.Load(this, ref _customers);
            set => _customers = worth;
 

Disabling Lazy Loading

You’ll be able to flip off lazy loading on the db context stage by setting the LazyLoadingEnabled property to false as proven within the code snippet beneath:

ChangeTracker.LazyLoadingEnabled = false;

Here is the up to date model of the NorthwindModelOptimized class with the above change included.

public sealed class NorthwindModelOptimized: NorthwindModel

	public NorthwindModelOptimized()
	

  	ChangeTracker.QueryTrackingBehavior =
  	QueryTrackingBehavior.NoTracking;
  	this.ChangeTracker.LazyLoadingEnabled = false;
	

	protected override void OnModelCreating(ModelBuilder modelBuilder)
	
   		// Write your implementation right here
	

Abstract

Entity Framework Core, a light-weight cross-platform model of Entity Framework, offers you a normal technique to entry information from a number of information sources. It consists of help for each Keen Loading in addition to Lazy Loading. Albeit the advantages, each have their downsides as properly. For instance, you may disable lazy loading should you wouldn’t need to use it.


Supply hyperlink

About PARTH SHAH

Check Also

मंत्री मुकेश सहनी बोले- पर्दे के पीछे से हो रहा ‘खेल’, VIP विधायकों को गुमराह करने की कोशिश जारी

पटना: बिहार सरकार में मंत्री मुकेश सहनी के एनडीए की बैठक का बहिष्कार करने के …

Leave a Reply

Your email address will not be published. Required fields are marked *

x