• Home
  • About Us
  • Contact Us
  • Disclaimer
  • Privacy Policy
  • Terms & Conditions
Wednesday, October 21, 2026
freevirtualsolutions.com
  • Home
  • Virtual Assistant
  • Enterprise Technology
  • Customer Support
  • Marketing Support
  • Workforce Management
No Result
View All Result
  • Home
  • Virtual Assistant
  • Enterprise Technology
  • Customer Support
  • Marketing Support
  • Workforce Management
No Result
View All Result
Free Virtual Solutions
No Result
View All Result
Home Enterprise Technology

Entity Framework Core efficiency ideas

Ermias S. by Ermias S.
3 years ago
in Enterprise Technology
0
399
SHARES
2.3k
VIEWS
Share on FacebookShare on Twitter


Entity Framework Core (EF Core) is an open supply ORM (object-relational mapping) framework that bridges the hole between the thing mannequin of your utility and the info mannequin of your database. EF Core makes life less complicated by permitting you to work with the database utilizing .NET objects, as an alternative of getting to put in writing information entry code.

In different phrases, EF Core permits 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. You’ll be able to extra simply retrieve entities from the info retailer, add, change, and delete entities, and traverse entity graphs by working straight in C#.

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

To work with the code examples supplied under, you must 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 utility mission in Visible Studio

First off, let’s create a .NET Core console utility mission in Visible Studio. Assuming Visible Studio 2022 is put in in your system, comply with the steps outlined under to create a brand new .NET Core console utility mission.

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

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

Retrieve solely the info you want

When coping with huge volumes of knowledge, you must try to retrieve solely the required data for the particular question. When fetching information, you must use projections to select simply the required fields and keep away from retrieving pointless fields.

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

Break up your massive information context into many smaller information contexts

The information context in your utility represents your database. Therefore, chances are you’ll ponder whether the applying 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 an alternative of utilizing a single huge information context, you must break the info context into quite a few 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 lengthen it from the DbContext class.

Use batch updates for big 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 big efficiency overhead. To alter this habits and optimize batch updates, you may reap the benefits of the UpdateRange() technique as proven within the code snippet given under.

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<Guide> Books { get; set; }
  }

Should you’re utilizing EF Core 7 or later, you should utilize the ExecuteUpdate and ExecuteDelete strategies to carry out batch updates and get rid of 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 while you need to replace an entity with new information, however it’s a expensive operation while you’re coping with massive information units. Therefore, you may enhance efficiency by disabling monitoring while you gained’t be modifying the entities.

For read-only queries, i.e., while you need to retrieve entities with out modifying them, you must 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 under reveals how one can retrieve entities straight 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 utility sometimes has a number of information 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 decreasing the overhead concerned in constructing and disposing of DbContext objects. Your utility might 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.Providers.AddDbContextPool<MyDbContext>(choices => choices.UseSqlServer(connection));

Use IQueryable as an alternative of IEnumerable

Once you’re quering information in EF Core, use IQueryable as an alternative of IEnumerable. Once you use IQueryable, the SQL statements can be executed on the server aspect, the place the info is saved, whereas IEnumerable requires the question to be executed on the shopper aspect. Furthermore, whereas IQueryable helps question optimizations and lazy loading, IEnumerable doesn’t. This explains why IQueryable executes queries sooner than IEnumerable.

The next code snippet reveals how you should utilize IQueryable to question information.

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 an alternative 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 information aren’t loaded until they’re wanted. Nonetheless, lazy loading might be expensive when it comes to efficiency as a result of a number of database queries could also be required to load the info.

To unravel this downside for particular eventualities, you should utilize keen loading in EF Core. Keen loading fetches your entities and associated entities in a single question, decreasing 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 express loading), lazy loading appears to alleviate the developer from coping with associated entities fully. As a result of EF Core is adept at robotically loading associated entities from the database when accessed by your code, lazy loading looks as if a pleasant function.

Nonetheless, lazy loading is very vulnerable 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 information context:

ChangeTracker.LazyLoadingEnabled = false;

Use asynchronous as an alternative of synchronous code

It is best to use async code to enhance the efficiency and responsiveness of your utility. Beneath I’ll share a code instance that reveals how one can execute queries asynchronously in EF Core. First, think about the next two mannequin courses.

public class Creator
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public Record<Guide> Books { get; set; }
}
public class Guide
{
    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 information 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<Guide> Books { get; set; }
}

Notice that we’re utilizing an in-memory database right here for simplicity. The next code snippet illustrates how you should utilize 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();
}

Cut back the spherical journeys to the database

You’ll be able to 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 identify refers back to the downside of sending N+1 small queries to the database to retrieve information that might be retrieved with one huge question.

In EF Core, the N+1 downside can happen while you’re making an attempt to load information from two tables having a one-to-many or many-to-many relationship. For instance, let’s say you’re loading creator information from the Authors desk and likewise e book information 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());
}

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

To unravel this downside, you must fetch the associated information prematurely (utilizing keen loading) as a part of the “1” question. In different phrases, you must embody the e book information in your preliminary question for the creator information, as proven within the code snippet given under.

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 by utilizing Embrace, we allow keen loading. The outer question, i.e., the entitiesQuery, executes simply as soon as to load all of the creator data along with the associated e book information. As an alternative of creating spherical journeys to the database, the 2 foreach loops work on the out there information within the reminiscence.

By the way, EF Core 7 reduces some spherical journeys to the database free of charge. The transaction administration for single insert statements was dropped from EF Core 7 as a result of it’s now not needed. 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 offers a big efficiency acquire when inserting information 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 utilize to enhance information entry efficiency in EF Core. Moreover, you must fine-tune your database design, indexes, queries, and saved procedures to get most advantages. Efficiency needs to be a function of your utility. It’s crucial that you just preserve efficiency in thoughts from the outset at any time when you’re constructing purposes that use quite a lot of information. 

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

Copyright © 2023 IDG Communications, Inc.



Source_link

Tags: CoreEntityframeworkPerformanceTips
Previous Post

Zoom’s AI phrases overhaul set the stage for broader knowledge use scrutiny

Next Post

Find out how to Construct Data Bridges by Unbiased Professionals

Next Post
Find out how to Construct Data Bridges by Unbiased Professionals

Find out how to Construct Data Bridges by Unbiased Professionals

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Categories

  • Customer Support (1,832)
  • Enterprise Technology (4,678)
  • Marketing Support (3,975)
  • Virtual Assistant (4,281)
  • Workforce Management (1,551)

Free Virtual Solutions

Welcome to freevirtualsolutionsThe goal of freevirtualsolutions is to give you the absolute best news sources for any topic! Our topics are carefully curated and constantly updated as we know the web moves fast so we try to as well.

Category

  • Customer Support
  • Enterprise Technology
  • Marketing Support
  • Virtual Assistant
  • Workforce Management

Recent Post

  • Walmart Chief People Officer Says This Is How to Get Promoted
  • Can Automotive Brands Win Loyalty By Competing On Price Alone?
  • What SMBs Need to Know to Protect Their Business
  • Home
  • About Us
  • Contact Us
  • Disclaimer
  • Privacy Policy
  • Terms & Conditions

Copyright © 2023 Freevirtualsolutions.com | All Rights Reserved.

No Result
View All Result
  • Home
  • Virtual Assistant
  • Enterprise Technology
  • Customer Support
  • Marketing Support
  • Workforce Management

Copyright © 2023 Freevirtualsolutions.com | All Rights Reserved.

Chat with us

Hi there! How can I help you?