You’ll be able to enhance information 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 suggestions and tips that may assist you to enhance the efficiency of your ASP.NET Core 7 purposes that use EF Core 7.
To work with the code samples supplied on this article, it’s essential to have Visible Studio 2022 Preview put in in your system. When you do not have already got a replica, you possibly can obtain Visible Studio 2022 Preview right here.
Create a minimal ASP.NET Core Internet API challenge in Visible Studio 2022 Preview
First, let’s create an ASP.NET Core challenge in Visible Studio 2022. Following these steps will create a brand new ASP.NET Core Internet API 7 challenge in Visible Studio 2022:
- Begin the Visible Studio 2022 Preview IDE.
- Click on “Create new challenge”.
- Within the “Create New Mission” window, choose “ASP.NET Core Internet API” from the checklist of templates displayed.
- Click on Subsequent.
- Within the “Arrange your new challenge” window, specify the identify and placement of the brand new challenge.
- Optionally, examine the “Place resolution and challenge in the identical listing” checkbox, relying in your preferences.
- Click on Subsequent.
- Within the “Extra Data” window under, underneath Framework, choose .NET 7.0 (Preview).
- Uncheck the checkbox that claims “Use controllers…” as we will probably be utilizing minimal APIs on this instance. Depart “Authentication Sort” set to “None” (default).
- Be sure the “Allow Docker”, “Configure for HTTPS”, and “Allow Open API Assist” checkboxes aren’t checked, as we cannot be utilizing any of these options right here.
- Click on Create.
We’ll use this ASP.NET Core 7 Internet API challenge to work with Entity Framework Core 7 in later sections of this text.
What’s Entity Framework Core?
The Entity Framework is Microsoft’s Object Relational Mapper (ORM) for .NET. Entity Framework Core is the open supply, cross-platform model of the Entity Framework for .NET Core.
Entity Framework Core makes it simple to implement information entry in your .NET Core purposes as a result of it lets you work with the database utilizing .NET objects. EF Core lets you write code to carry out CRUD (create, learn, replace, delete) actions with out understanding how information is persevered within the underlying database. With EF Core, you possibly can extra simply retrieve entities from the info retailer, add, change, and delete entities, and traverse entity graphs.
EF Core efficiency finest practices
You’ll be able to assist EF Core carry out these information entry operations sooner by taking benefit of some finest practices. We’ll focus on 5 of those finest practices under.
Disable change monitoring for read-only situations
Each time you question for entities in your DbContext, the context tracks the returned objects so as to modify them and persist the modifications. If the question is a read-only question, that’s, no modifications will probably be made to the returned information, then the context just isn’t required to carry out that process. It is best to disable change monitoring if it’s not required.
You’ll be able to disable change monitoring for particular person queries by together with the AsNoTracking methodology within the question. When utilizing the AsNoTracking methodology, EF Core skips the additional effort of monitoring entities, which improves efficiency (particularly for queries involving a lot of entities).
Extra importantly, you do not want change monitoring if you solely intend to retrieve information in your software. In different phrases, should you simply wish to retrieve information from the info context, with out inserting, updating, or deleting information, then you definately needn’t allow this characteristic. You’ll be able to disable object monitoring by including the next code to your information context class.
ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking;
The underside line is that queries that use AsNoTracking will execute sooner than queries that do not. Nevertheless, keep in mind that you must by no means use AsNoTracking in queries that insert, edit, or delete entities. Additionally, if you want to insert, edit, or delete information utilizing the info context, you must keep away from specifying the QueryTrackingBehavior on the information context degree.
Recuperate solely the info you want
When coping with huge volumes of information, you must try to retrieve solely the data wanted for the precise question. When getting information, you must use projections to pick out solely required fields. It is best to keep away from retrieving pointless fields. The next code snippet reveals easy methods to get information paginated. Notice how the index of the preliminary web page and the web page dimension have been used to decide on solely the required information.
int pageSize = 50, startingPageIndex = 1;
var dataContext = new OrderProcessingDbContext();
var information = dataContext.Orders.Take(pageSize)
.Skip(startingPageIndex * pageSize)
Break up your large information context into many smaller information contexts
The info context in your software represents your database. So it’s possible you’ll be questioning if the appliance ought to have solely a number of information contexts. In Entity Framework Core, the startup time of a big information context represents a big efficiency constraint. Because of this, as a substitute of utilizing a single massive information context, it’s essential to cut up the info context into many smaller information contexts.
Ideally, you must solely have one information context per module or unit of labor. To make use of a number of information contexts, merely create a brand new class for every information context and prolong it from the DbContext class.
Disable lazy loading
Lazy loading is a characteristic that removes the necessity to load pointless associated entities (as in specific loading) and appears to forestall the developer from coping with associated entities totally. Since EF Core is adept at routinely loading associated entities from the database if you entry your code, lazy loading looks like a pleasant characteristic.
Nevertheless, lazy loading is particularly vulnerable to pointless extra spherical journeys, which may decelerate your software. You’ll be able to disable lazy loading by specifying the next in your information context:
ChangeTracker.LazyLoadingEnabled = false;
Use the DbContext pool
An software sometimes has a number of information contexts. As a result of DbContext objects could be costly to create and eliminate, EF Core offers a mechanism to pool them. By pooling, DbContext objects are created as soon as after which reused as wanted.
Utilizing a DbContext group in EF Core can enhance efficiency by lowering the overhead concerned in creating and deleting DbContext objects. Because of this, your software may use much less reminiscence.
The next code snippet illustrates how one can configure the DbContext pool within the Program.cs file.
builder.Companies.AddDbContextPool<MyDbContext>(choices => choices.UseSqlServer(connection));
This text supplied a dialogue of finest practices that may be adopted to enhance information entry efficiency in EF Core. In fact, every software has totally different information entry necessities and traits. It is best to examine the efficiency of EF Core earlier than and after making use of these modifications to evaluate the outcomes on your particular software. A wonderful device for the duty is BenchmarkDotNet, which you’ll examine in a earlier put up.
Copyright © 2022 IDG Communications, Inc.
– Entity Framework Core performance tips