Thursday, October 20, 2022
HomeITEntity Framework Core efficiency ideas

Entity Framework Core efficiency ideas


You’ll be able to enhance knowledge entry efficiency in Entity Framework Core in a number of methods. These embrace enabling keen loading, disabling lazy loading, utilizing streaming as a substitute of buffering, and disabling change monitoring. On this article, we’ll discover a number of the ideas and tips that may provide help to enhance the efficiency of your ASP.NET Core 7 purposes that make use of EF Core 7.

To work with the code examples offered on this article, you need to have Visible Studio 2022 Preview put in in your system. If you happen to don’t have already got a duplicate, you may obtain Visible Studio 2022 Preview right here.

Create an ASP.NET Core minimal Internet API mission in Visible Studio 2022 Preview

First off, let’s create an ASP.NET Core mission in Visible Studio 2022. Following these steps will create a brand new ASP.NET Core Internet API 7 mission in Visible Studio 2022:

  1. Launch the Visible Studio 2022 Preview IDE.
  2. Click on on “Create new mission.”
  3. Within the “Create new mission” window, choose “ASP.NET Core Internet API” from the record of templates displayed.
  4. Click on Subsequent.
  5. Within the “Configure your new mission” window, specify the title and site for the brand new mission.
  6. Optionally verify the “Place resolution and mission in the identical listing” verify field, relying in your preferences.
  7. Click on Subsequent.
  8. Within the “Extra Data” window proven subsequent, below Framework, choose .NET 7.0 (Preview).
  9. Uncheck the verify field that claims “Use controllers…” since we’ll be utilizing minimal APIs on this instance. Go away the “Authentication Kind” set to “None” (default).
  10. Make sure that the verify bins “Allow Docker,” “Configure for HTTPS,” and “Allow Open API Help” are unchecked as we received’t be utilizing any of these options right here.
  11. Click on Create.

We’ll use this ASP.NET Core 7 Internet API mission to work with Entity Framework Core 7 within the subsequent sections of this text.

What’s Entity Framework Core?

Entity Framework is Microsoft’s object-relational mapper (ORM) for .NET. Entity Framework Core is the open-source, cross-platform model of Entity Framework for .NET Core. 

Entity Framework Core makes it simpler to implement knowledge entry in your .NET Core purposes as a result of it permits you to work with the database utilizing .NET objects. EF Core enables you to write code to execute CRUD actions (create, learn, replace, and delete) with out understanding how the info is endured within the underlying database. Utilizing EF Core, you may extra simply retrieve entities from the info retailer, add, change, and delete entities, and traverse entity graphs.

EF Core efficiency greatest practices

You’ll be able to assist EF Core carry out these knowledge entry operations extra speedily by taking benefit of some greatest practices. We’ll talk about 5 of those greatest practices beneath.

Disable change monitoring for read-only situations

Everytime you question entities in your DbContext, the context tracks the returned objects with the intention to alter them and protect the modifications. If the question is a read-only question, i.e., if no modifications will likely be made to the returned knowledge, then the context will not be required to carry out that process. It is best to disable change monitoring if it isn’t required.

You’ll be able to disable change monitoring for particular person queries by together with the AsNoTracking technique within the question. When the AsNoTracking technique is used, EF Core will skip the additional effort of monitoring the entities, thereby bettering efficiency (particularly for queries involving giant numbers of entities).

Most significantly, you don’t want change monitoring once you solely intend to retrieve knowledge in your utility. In different phrases, for those who solely need to retrieve knowledge from the info context, with out inserting, updating, or deleting knowledge, then you definately don’t want this function to be turned on. You’ll be able to disable object monitoring by including the next code to your knowledge context class.

ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking;

The underside line is that queries that use AsNoTracking will run quicker than queries that don’t use it. Nonetheless, keep in mind that you have to by no means use AsNoTracking in queries that insert, edit, or delete entities. Moreover, if you have to insert, edit, or delete knowledge utilizing the info context, you need to keep away from specifying the QueryTrackingBehavior on the knowledge context degree.

Retrieve solely the info you want

When coping with huge volumes of knowledge, you need to attempt to retrieve solely the required information for the precise question. When fetching knowledge, you need to use projections to select simply the required fields. It is best to keep away from retrieving pointless fields. The next code snippet exhibits tips on how to get hold of knowledge in a paged vogue. Discover how the start web page index and web page dimension have been used to decide on simply the required knowledge.

int pageSize = 50, startingPageIndex = 1;
var dataContext = new OrderProcessingDbContext();
var knowledge = dataContext.Orders.Take(pageSize)
.Skip(startingPageIndex * pageSize)
.ToList();

Cut up your giant knowledge context into many smaller knowledge contexts

The information context in your utility represents your database. Therefore, chances are you’ll wonder if the applying ought to have solely a number of knowledge contexts. In Entity Framework Core, the startup time of a giant knowledge context represents a major efficiency constraint. In consequence, as a substitute of utilizing a single huge knowledge context, you need to break the info context into quite a few smaller knowledge contexts.

Ideally, you need to solely have one knowledge context per module or unit of labor. To make use of a number of knowledge contexts, merely create a brand new class for every knowledge context and prolong it from the DbContext class.

Disable lazy loading

Lazy loading is a function that eliminates the necessity to load pointless associated entities (as in specific loading) and appears to take away the developer from coping with associated entities solely. As a result of EF Core is adept at mechanically loading associated entities from the database when accessed by your code, lazy loading looks as if a pleasant function.

Nonetheless, lazy loading is very liable to producing pointless extra spherical journeys, which may decelerate your utility. You’ll be able to flip off lazy loading by specifying the next in your knowledge context:

ChangeTracker.LazyLoadingEnabled = false;

Use DbContext pooling

An utility usually has a number of knowledge contexts. As a result of DbContext objects could also be pricey to create and get rid of, EF Core provides a mechanism for pooling them. By pooling, DbContext objects are created as soon as, then reused when wanted.

Utilizing a DbContext pool in EF Core can enhance efficiency by decreasing the overhead concerned in constructing and disposing of DbContext objects. Your utility may additionally use much less reminiscence consequently.

The next code snippet illustrates how one can configure DbContext pooling within the Program.cs file.

builder.Companies.AddDbContextPool<MyDbContext>(choices => choices.UseSqlServer(connection));

This text offered a dialogue of greatest practices that may be adopted to enhance knowledge entry efficiency in EF Core. After all, each utility has totally different knowledge entry necessities and traits. It is best to benchmark your EF Core efficiency earlier than and after you apply these modifications to evaluate the outcomes in your particular utility. A wonderful instrument for the duty is BenchmarkDotNet, which you’ll be able to examine in a earlier publish.

Copyright © 2022 IDG Communications, Inc.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments