Logo

dev-resources.site

for different kinds of informations.

The Differences Between EntityFramework .Add and .AddAsync

Published at
7/3/2024
Categories
csharp
softwaredevelopment
entityframework
Author
tkarropoulos
Author
12 person written this
tkarropoulos
open
The Differences Between EntityFramework .Add and .AddAsync

Introduction

Entity Framework is a popular Object-Relational Mapper (ORM) for .NET, which allow us to better interact with a database using .NET objects. One of the fundamental operations we are using all of us that interact with databases is adding new entities. In this article I will try to explain the two methods that we have in our disposal for entities creation Add and AddAsync. We will explore their usage, differences and best practices for when to use each other.

What is DbSet<TEntity>.Add?

The DbSet.Add method is a synchronous method used to add a new entity to the context, which is then tracked by EF Core. When SaveChanges is called, EF Core generates the necessary SQL statements to insert the new entity into the database.
Lets see a usage example of Add method

public Task AddNewEntityAsync(Entity entity, CancellationToken ct)
{
    using (var context = new ApplicationDbContext())
    {
        context.Entities.Add(entity);
        await context.SaveChangesAsync(ct);
    }
}

Enter fullscreen mode Exit fullscreen mode

How the above example works,

  • The Add method attaches the entity to the context with an Added state
  • When SaveChangesAsync is called the context creates an INSERT SQL command to add the entity to the database asynchronously

What is DbSet<TEntity>.AddAsync?

The AddAsync method is the asynchronous counterpart of the Add method. It is used to add a new entity to the context asynchronously. A usage example of AddAsync is given bellow

public async Task AddAsync(Entity entity)
{
    using (var context = new ApplicationDbContext())
    {
        await context.Entities.AddAsync(entity);
        await context.SaveChangesAsync();
    }
}
Enter fullscreen mode Exit fullscreen mode

How it works
The AddAsync method attaches the entity to the context with an Added state asynchronously

  • When SaveChangesAsync is called, the context creates an INSERT SQL command to add the entity to the database asynchronously

Key Differences Between Add and AddAsync

Now the first question that pops in our minds is ok, so I will use Add when I am in a synchronous context and AddAsync when I am in asynchronous.
This is just one aspect; the other is how Add and AddAsync interact with the database.
As Microsoft explains

This method is async only to allow special value generators, such as the one used by 'Microsoft.EntityFrameworkCore.Metadata.SqlServerValueGenerationStrategy.SequenceHiLo', to access the database asynchronously. For all other cases the non async method should be used.

That simple means that event though Add and AddAsync are doing the same thing, AddAsync comes with a little overhead and that is an extra interaction with the database, something that is avoided with the use of Add

If you found my article useful, feel free to share it. Also, leave a comment if something is not clear enough.

entityframework Article's
30 articles in total
Favicon
Entity Framework Core Code First
Favicon
Code First Approach with Entity Framework.
Favicon
Custom NET8 Entity Framework Core Generic Repository
Favicon
Link Many To Many entities with shadow join-table using Entity Framework Core
Favicon
Running Entity Framework Core Migrations with Optimizely CMS 12
Favicon
Check Pagination in .NET: With and Without Entity Framework
Favicon
EF Core 6 - correct types halving the execution time!
Favicon
EF Core 6 - This SqlTransaction has completed; it is no longer usable.
Favicon
Entity Framework Core Tutorial:Introduction to Entity Framework Core
Favicon
ReadOnly DbContext with Entity Framework
Favicon
[KOSD] Multiple Parallel Operations in Entity Framework Core (.NET 8)
Favicon
Entity Framework in .net core 6.0 - Code first and Database first approach
Favicon
5 EF Core Features You Need To Know
Favicon
C# | Best Practices for Pagination using EF Core 8
Favicon
C# | Using Entity Framework with PostgreSQL Database
Favicon
C# | Entity Framework Generic Repository with SOLID Design Pattern
Favicon
C# | Entity Framework Issues and Troubleshooting
Favicon
Entity Framework Core with Scalar Functions
Favicon
Prefer Empty Objects over Compiler tricks
Favicon
The Differences Between EntityFramework .Add and .AddAsync
Favicon
Entity FrameWork
Favicon
Load Appointments on Demand in Blazor Scheduler using Entity Framework Core
Favicon
Finding the Right Balance: Clean Architecture and Entity Framework in Practice
Favicon
Compilation steps in EF Core
Favicon
Learning is another full-time job.
Favicon
How To Use EF Core Interceptors
Favicon
Using Entity Framework Core 8 Owned Types HasData()
Favicon
Simple Event-Sourcing with EF Core and SQL Server
Favicon
Delete in EF 8 !
Favicon
Optimizing Database Access with Entity Framework - Lazy Loading vs. Eager Loading

Featured ones: