Wednesday, May 14, 2025

Entity Framework Core efficiency suggestions


Entity Framework Core (EF Core) is an open supply ORM (object-relational mapping) framework that bridges the hole between the article mannequin of your software and the information mannequin of your database. EF Core makes life easier by permitting you to work with the database utilizing .NET objects, as a substitute of getting to write down knowledge entry code.

In different phrases, 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. You possibly can extra simply retrieve entities from the information retailer, add, change, and delete entities, and traverse entity graphs by working immediately in C#.

You possibly can enhance knowledge entry efficiency in EF Core in many various methods, starting from utilizing keen loading to lowering the database spherical journeys required by your queries. On this article, we’ll discover 10 suggestions and methods or methods we are able to use in EF Core to enhance the information entry efficiency of our .NET Core purposes.

To work with the code examples supplied beneath, it is best to have Visible Studio 2022 put in in your system. Should you don’t have already got a replica, you may obtain Visible Studio 2022 right here.

Create a console software venture in Visible Studio

First off, let’s create a .NET Core console software venture in Visible Studio. Assuming Visible Studio 2022 is put in in your system, observe the steps outlined beneath to create a brand new .NET Core console software venture.

  1. Launch the Visible Studio IDE.
  2. Click on on “Create new venture.”
  3. Within the “Create new venture” window, choose “Console App (.NET Core)” from the listing of templates displayed.
  4. Click on Subsequent.
  5. Within the “Configure your new venture” window, specify the title and placement for the brand new venture.
  6. Click on Subsequent.
  7. Within the “Extra info” window proven subsequent, select “.NET 7.0 (Normal Time period Assist)” because the Framework model you need to use.
  8. Click on Create.

We’ll use this venture to work with EF Core 7 all through this text. Within the sections that observe, we’ll focus on 10 methods we are able to enhance knowledge entry pace in EF Core, illustrated by code examples wherever applicable. Let’s get began!

Retrieve solely the information you want

When coping with large volumes of knowledge, it is best to try to retrieve solely the required information for the particular question. When fetching knowledge, it is best to use projections to choose simply the required fields and keep away from retrieving pointless fields.

The next code snippet reveals methods to get hold of knowledge in a paged style. 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();

Break up your massive knowledge context into many smaller knowledge contexts

The information context in your software represents your database. Therefore, it’s possible you’ll wonder if the applying ought to have solely a number of knowledge contexts. In Entity Framework Core, the startup time of a big knowledge context represents a major efficiency constraint. Because of this, as a substitute of utilizing a single huge knowledge context, it is best to break the information context into quite a few smaller knowledge contexts.

Ideally, it is best 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 lengthen it from the DbContext class.

Use batch updates for giant numbers of entities

The default habits of EF Core is to ship particular person replace statements to the database when there’s a batch of replace statements to be executed. Naturally, a number of hits to the database entail a major efficiency overhead. To alter this habits and optimize batch updates, you may make the most of the UpdateRange() methodology as proven within the code snippet given beneath.

public class DataContext : DbContext
  {
      public void BatchUpdateAuthors(Record<Creator> authors)
      {
          var college students = this.Authors.The place(a => a.Id >10).ToList();
          this.UpdateRange(authors);
          SaveChanges();
      }
      protected override void OnConfiguring
      (DbContextOptionsBuilder choices)
      {
          choices.UseInMemoryDatabase("AuthorDb");
      }
      public DbSet<Creator> Authors { get; set; }
      public DbSet<E-book> Books { get; set; }
  }

Should you’re utilizing EF Core 7 or later, you should use the ExecuteUpdate and ExecuteDelete strategies to carry out batch updates and eradicate a number of database hits. For instance:

_context.Authors.The place(a => a.Id > 10).ExecuteUpdate();

Disable change monitoring for read-only queries

The default habits of EF Core is to trace objects retrieved from the database. Monitoring is required if you need to replace an entity with new knowledge, however it’s a expensive operation if you’re coping with massive knowledge units. Therefore, you may enhance efficiency by disabling monitoring if you received’t be modifying the entities.

For read-only queries, i.e., if you need to retrieve entities with out modifying them, it is best to use AsNoTracking to enhance efficiency. The next code snippet illustrates how AsNoTracking can be utilized to disable monitoring for a person question in EF Core.

var dbModel = await this._context.Authors.AsNoTracking()
    .FirstOrDefaultAsync(e => e.Id == creator.Id);

The code snippet given beneath reveals how one can retrieve entities immediately from the database for read-only functions, with out monitoring and with out loading them into the reminiscence.

public class DataContext : DbContext
{
    public IQueryable<Creator> GetAuthors()
    {
        return Set<Creator>().AsNoTracking();
    }
}

Use DbContext pooling

An software usually has a number of knowledge contexts. As a result of DbContext objects could also be expensive to create and eliminate, EF Core gives 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 may use much less reminiscence in consequence.

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

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

Use IQueryable as a substitute of IEnumerable

Whenever you’re quering knowledge in EF Core, use IQueryable as a substitute of IEnumerable. Whenever you use IQueryable, the SQL statements will probably be executed on the server facet, the place the information is saved, whereas IEnumerable requires the question to be executed on the consumer facet. Furthermore, whereas IQueryable helps question optimizations and lazy loading, IEnumerable doesn’t. This explains why IQueryable executes queries quicker than IEnumerable.

The next code snippet reveals how you should use IQueryable to question knowledge.

IQueryable<Creator> question = _context.Authors;
question = question.The place(e => e.Id == 5);
question = question.OrderBy(e => e.Id);
Record<Creator> entities = question.ToList();

Use keen loading as a substitute of lazy loading

EF Core makes use of lazy loading by default. With lazy loading, the associated entities are loaded into the reminiscence solely when they’re accessed. The profit is that knowledge aren’t loaded except they’re wanted. Nonetheless, lazy loading might be expensive by way of efficiency as a result of a number of database queries could also be required to load the information.

To unravel this downside for particular eventualities, you should use keen loading in EF Core. Keen loading fetches your entities and associated entities in a single question, lowering the variety of spherical journeys to the database. The next code snippet reveals how keen loading can be utilized.

public class DataContext : DbContext
{
    public Record<Creator> GetEntitiesWithEagerLoading()
    {
        Record<Creator> entities = this.Set<Creator>()
            .Embrace(e => e.Books)
            .ToList();
        return entities;
    }
}

Disable lazy loading

By eliminating the necessity to load pointless associated entities (as in specific loading), lazy loading appears to alleviate the developer from coping with associated entities fully. 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 particularly vulnerable to producing pointless extra spherical journeys, which may decelerate your software. You possibly can flip off lazy loading by specifying the next in your knowledge context:

ChangeTracker.LazyLoadingEnabled = false;

Use asynchronous as a substitute of synchronous code

You need to use async code to enhance the efficiency and responsiveness of your software. Under I’ll share a code instance that reveals how one can execute queries asynchronously in EF Core. First, contemplate the next two mannequin lessons.

public class Creator
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public Record<E-book> Books { get; set; }
}
public class E-book
{
    public int Id { get; set; }
    public string Title { get; set; }
    public Creator Creator { get; set; }
}

Within the code snippet that follows, we’ll create a customized knowledge context class by extending the DbContext class of EF Core library.

public class DataContext : DbContext
{
    protected readonly IConfiguration Configuration;
    public DataContext(IConfiguration configuration)
    {
        Configuration = configuration;
    }
    protected override void OnConfiguring
    (DbContextOptionsBuilder choices)
    {
        choices.UseInMemoryDatabase("AuthorDb");
    }
    public DbSet<Creator> Authors { get; set; }
    public DbSet<E-book> Books { get; set; }
}

Word that we’re utilizing an in-memory database right here for simplicity. The next code snippet illustrates how you should use async code to replace an entity within the database utilizing EF Core.

public async Activity<int> Replace(Creator creator)
{
    var dbModel = await this._context.Authors
       .FirstOrDefaultAsync(e => e.Id == creator.Id);
       dbModel.Id = creator.Id;
       dbModel.FirstName = creator.FirstName;
       dbModel.LastName = creator.LastName;
       dbModel.Books = creator.Books;
       return await this._context.SaveChangesAsync();
}

Scale back the spherical journeys to the database

You possibly can considerably cut back the variety of spherical journeys to the database by avoiding the N+1 selects downside. The N+1 selects downside has plagued database efficiency because the early days of ORMs. The title refers back to the downside of sending N+1 small queries to the database to retrieve knowledge that could possibly be retrieved with one large question.

In EF Core, the N+1 downside can happen if you’re attempting to load knowledge from two tables having a one-to-many or many-to-many relationship. For instance, let’s say you’re loading creator knowledge from the Authors desk and likewise guide knowledge from the Books desk. Think about the next piece of code.

foreach (var creator on this._context.Authors)
{
    creator.Books.ForEach(b => b.Title.ToUpper());
}

Word that the outer foreach loop will fetch all authors utilizing one question. That is the “1” in your N+1 queries. The inside foreach that fetches the books represents the “N” in your N+1 downside, as a result of the inside foreach will probably be executed N instances.

To unravel this downside, it is best to fetch the associated knowledge upfront (utilizing keen loading) as a part of the “1” question. In different phrases, it is best to embrace the guide knowledge in your preliminary question for the creator knowledge, as proven within the code snippet given beneath.

var entitiesQuery = this._context.Authors
    .Embrace(b => b.Books);
foreach (var entity in entitiesQuery)
{
   entity.Books.ForEach(b => b.Title.ToUpper());
}

By doing so, you cut back the variety of spherical journeys to the database from N+1 to only one. It’s because through the use of Embrace, we allow keen loading. The outer question, i.e., the entitiesQuery, executes simply as soon as to load all of the creator information along with the associated guide knowledge. As an alternative of creating spherical journeys to the database, the 2 foreach loops work on the out there knowledge within the reminiscence.

By the way, EF Core 7 reduces some spherical journeys to the database totally free. How so? The transaction administration for single insert statements was dropped from EF Core 7 as a result of it’s not vital. Because of this, EF Core 7 omits two spherical journeys that had been utilized in earlier variations of EF Core to start and commit a transaction. The upshot is that EF Core 7 supplies a major efficiency achieve when inserting knowledge right into a database utilizing a single insert assertion in comparison with predecessors.

Efficiency needs to be a function

On this article we examined 10 key methods you should use to enhance knowledge entry efficiency in EF Core. Moreover, it is best to fine-tune your database design, indexes, queries, and saved procedures to get most advantages. Efficiency needs to be a function of your software. It’s crucial that you simply preserve efficiency in thoughts from the outset each time you’re constructing purposes that use numerous knowledge. 

Lastly, each software has completely different knowledge entry necessities and traits. You need to benchmark your EF Core efficiency earlier than and after you apply any of the adjustments we mentioned right here to evaluate the outcomes on your particular software. A wonderful software for the duty is BenchmarkDotNet, which you’ll be able to examine in my earlier publish right here.

Copyright © 2023 IDG Communications, Inc.

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Stay Connected

0FansLike
3,912FollowersFollow
0SubscribersSubscribe
- Advertisement -spot_img

Latest Articles