You possibly can 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 are going to discover a few of the ideas and tips that may assist you to enhance the efficiency of your ASP.NET Core 7 purposes that make use of EF Core 7.
To work with the code examples supplied on this article, it is best to have Visible Studio 2022 Preview put in in your system. In the event you don’t have already got a duplicate, you may download Visual Studio 2022 Preview here.
Create an ASP.NET Core minimal Internet API venture in Visible Studio 2022 Preview
First off, let’s create an ASP.NET Core venture in Visible Studio 2022. Following these steps will create a brand new ASP.NET Core Internet API 7 venture in Visible Studio 2022:
- Launch the Visible Studio 2022 Preview IDE.
- Click on on “Create new venture.”
- Within the “Create new venture” window, choose “ASP.NET Core Internet API” from the checklist of templates displayed.
- Click on Subsequent.
- Within the “Configure your new venture” window, specify the title and site for the brand new venture.
- Optionally examine the “Place answer and venture in the identical listing” examine field, relying in your preferences.
- Click on Subsequent.
- Within the “Further Info” window proven subsequent, underneath Framework, choose .NET 7.0 (Preview).
- Uncheck the examine field that claims “Use controllers…” since we’ll be utilizing minimal APIs on this instance. Go away the “Authentication Sort” set to “None” (default).
- Be sure that the examine containers “Allow Docker,” “Configure for HTTPS,” and “Allow Open API Help” are unchecked as we gained’t be utilizing any of these options right here.
- Click on Create.
We’ll use this ASP.NET Core 7 Internet API venture 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 information entry in your .NET Core purposes as a result of it means that you can 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 information is endured within the underlying database. Utilizing EF Core, you may extra simply retrieve entities from the information retailer, add, change, and delete entities, and traverse entity graphs.
EF Core efficiency greatest practices
You possibly can assist EF Core carry out these information entry operations extra speedily by taking benefit of some greatest practices. We’ll talk about 5 of those greatest practices under.
Disable change monitoring for read-only eventualities
Everytime you question entities in your DbContext, the context tracks the returned objects so as to alter them and protect the modifications. If the question is a read-only question, i.e., if no modifications might be made to the returned information, then the context shouldn’t be required to carry out that process. You must disable change monitoring if it isn’t required.
You possibly can 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 enhancing efficiency (particularly for queries involving massive numbers of entities).
Most significantly, you do not want change monitoring once you solely intend to retrieve information in your software. In different phrases, for those who solely wish to retrieve information from the information context, with out inserting, updating, or deleting information, then you definately don’t want this function to be turned on. You possibly can 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 run sooner than queries that don’t use it. Nonetheless, do not forget that it’s essential to by no means use AsNoTracking in queries that insert, edit, or delete entities. Moreover, if it’s good to insert, edit, or delete information utilizing the information context, it is best to keep away from specifying the QueryTrackingBehavior on the information context degree.
Retrieve solely the information you want
When coping with large volumes of knowledge, it is best to attempt to retrieve solely the required data for the particular question. When fetching information, it is best to use projections to select simply the required fields. You must keep away from retrieving pointless fields. The next code snippet reveals the right way to receive information in a paged trend. Discover how the start web page index and web page measurement have been used to decide on simply the required information.
int pageSize = 50, startingPageIndex = 1;
var dataContext = new OrderProcessingDbContext();
var information = dataContext.Orders.Take(pageSize)
.Skip(startingPageIndex * pageSize)
Cut up your massive information context into many smaller information contexts
The info context in your software represents your database. Therefore, you could wonder if the appliance ought to have solely a number of information contexts. In Entity Framework Core, the startup time of a giant information context represents a big efficiency constraint. Because of this, as a substitute of utilizing a single huge information context, it is best to break the information context into quite a few smaller information contexts.
Ideally, it is best to 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 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 routinely loading associated entities from the database when accessed by your code, lazy loading looks as if a pleasant function.
Nonetheless, lazy loading is very susceptible to producing pointless further spherical journeys, which might decelerate your software. You possibly can flip off lazy loading by specifying the next in your information context:
ChangeTracker.LazyLoadingEnabled = false;
Use DbContext pooling
An software sometimes has a number of information contexts. As a result of DbContext objects could also be pricey to create and get rid of, EF Core presents 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 lowering the overhead concerned in constructing and disposing of DbContext objects. Your software can also use much less reminiscence because of this.
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 supplied a dialogue of greatest practices that may be adopted to enhance information entry efficiency in EF Core. After all, each software has totally different information entry necessities and traits. You must benchmark your EF Core efficiency earlier than and after you apply these modifications to evaluate the outcomes on your particular software. A superb software for the duty is BenchmarkDotNet, which you’ll be able to examine in a previous post.