How to work with disconnected entities in Entity Framework Core

Entity Framework is an open source, object-relational mapper (ORM) that simplifies details accessibility in your application. It enables you to generate code to conduct CRUD (produce, study, update, and delete) functions with out acquiring to know how the info is persisted in the underlying database. Entity Framework Main is the edition of Entity Framework that runs on .Internet Core.

Entity Framework Main delivers procedures to retrieve entities from the facts store, to include, adjust, or delete entities, and to traverse entity graphs. Even though these methods function effectively in linked conditions, you may well often want to get the job done in a disconnected mode and nevertheless trace the full object graph. This is where by the ChangeTracker.TrackGraph system will come into participate in.

This short article discusses how we can use the ChangeTracker.TrackGraph strategy to do the job with disconnected entities in Entity Framework Core. To work with the code illustrations furnished in this post, you need to have Visual Studio 2022 installed in your technique. If you never already have a duplicate, you can down load Visual Studio 2022 in this article.

Build an ASP.Web Main Web API undertaking in Visual Studio 2022

Initially off, let us develop an ASP.Net Core project in Visual Studio 2022. Subsequent these ways will build a new ASP.Net Main World wide web API 6 job in Visual Studio 2022:

  1. Launch the Visual Studio 2022 IDE.
  2. Click on on “Create new undertaking.”
  3. In the “Create new project” window, select “ASP.Net Main Website API” from the checklist of templates shown.
  4. Click on Next.
  5. In the “Configure your new project” window, specify the title and place for the new job.
  6. Optionally verify the “Place answer and job in the exact same directory” check box, dependent on your preferences.
  7. Click on Up coming.
  8. In the “Additional Information” window demonstrated upcoming, choose .Net 6. as the concentrate on framework from the fall-down record at the best. Depart the “Authentication Type” as “None” (default).
  9. Guarantee that the test boxes “Enable Docker,” “Configure for HTTPS,” and “Enable Open up API Support” are unchecked as we will not be employing any of all those capabilities right here.
  10. Click on Produce.

This will create a new ASP.Web Core 6 World-wide-web API undertaking in Visual Studio 2022. We’ll use this venture in the subsequent sections of this post.

Put in the Entity Framework Core NuGet offers

If you have properly produced an ASP.Net Core 6 internet software task in Visual Studio 2022, the following point you must do is insert the vital NuGet offers to your project. To do this, pick out the task in the Resolution Explorer window, ideal-click and find “Manage NuGet Deals…” In the NuGet Bundle Supervisor window, search for the next offers, and put in them.

  • Set up-Bundle Microsoft.EntityFrameworkCore
  • Install-Deal Microsoft.EntityFrameworkCore.Tools
  • Install-Deal Microsoft.EntityFrameworkCore.SqlServer

Alternatively, you can install the offer by means of the NuGet Deal Manager Console as revealed underneath.

PM> Install-Offer Microsoft.EntityFrameworkCore
PM> Set up-Deal Microsoft.EntityFrameworkCore.Applications
PM> Install-Package Microsoft.EntityFrameworkCore.SqlServer

Monitor variations to an entity in Entity Framework Main

ADO.Net can operate in two diverse modes – linked and disconnected. Simply because Entity Framework Main is created on major of ADO.Web, it also supports equally related and disconnected modes of procedure.

In Entity Framework Core, the DbContext scenarios can be utilized to monitor entities that are retrieved from the database. When the SaveChanges technique is identified as, any modifications to these entities are regarded, and the databases is up to date properly. Nevertheless, examine functions on the entities are usually executed with one information context instance although a unique knowledge context instance is utilised to increase, update, or delete the entity.

This separation is widespread in “disconnected” contexts, such as in world-wide-web purposes, where by entities are searched, despatched to the customer, updated, returned in a ask for, and afterwards persisted to the databases. The second facts context occasion ought to know if the entities are new or if they are already offered.

The EntityState assets in Entity Framework Main

Entity Framework Main can take gain of a residence known as State to retain a observe of variations to an entity. This residence is available on all entities and is of variety EntityState. Alterations to this home occur when you use solutions these as Attach, Add, Entry, Update, or Remove.

The pursuing code snippet illustrates how you can update an entity in the info store.

employing (var dataContext = new DemoContext())

    var merchandise = dataContext.Merchandise.Solitary(p => p.Id == 7)
    item.Title = "Lenovo"
    item.Classification = "Laptop"
    context.SaveChanges()

Observe that when you’re doing work with Entity Framework Core in disconnected mode, you have to explicitly specify the entity that has changed. To do this, you can set the EntityState property we just talked about or use the DbContext.Update or DbContext.Attach strategy.

Use the TrackGraph technique in Entity Framework Main

The TrackGraph method is used in disconnected eventualities in which the entities are fetched from the info keep with a single instance of the context, and modifications to the entities are persisted in the facts retail store with another occasion of the context. The TrackGraph strategy traverses an entity’s navigation characteristics to observe all entities that are available, provided that the entity has not been tracked before.

The code snippet provided below displays how you can use the TrackGraph method.

var dbContext = new DemoContext()
  dbContext.ChangeTracker.TrackGraph(product or service, p =>
  if (p.Entry.IsKeySet)
  
       p.Entry.Condition = EntityState.Unchanged
  
   else
  
       p.Entry.State = EntityState.Additional
  
)

In this instance, if an entity has a key affiliated with it, then the entity is unchanged. By distinction, if a important is not associated with the entity, then it is clear that the entity has been added.

The subsequent code snippet illustrates how you can screen the condition and variety of all entities that are a part of the data context.

foreach (var entity in dbContext.ChangeTracker.Entries())

    _logger.LogInformation("Entity: , Condition: 1",
    entity.Entity.GetType().Name, entity.Condition.ToString())

Entity Framework Core can track only a single occasion of an entity with a principal key. The ideal possible way to manage this draw back is to use a shorter-lived context for every device of function, the place the context starts empty, has entities linked to it, and merchants people entities. At some point, when the device of work is finished, the context is disposed of and deleted.

Copyright © 2022 IDG Communications, Inc.