Difference between Add and AddAsync in EF Core
Using Add or AddAsync in Entity Framework Core can be a little confusing, especially for those new to working with databases and ORMs (Object-Relational Mappers). In this blog post, we'll take a look at the difference between
AddAsync, and when you might want to use one over the other.
First, let's define what these two methods do. Add is a method on the DbSet class in Entity Framework Core that is used to add a new entity to the database. It is a synchronous method, meaning that it will block the calling thread until the operation is complete. AddAsync, on the other hand, is an asynchronous version of Add that allows you to add a new entity to the database without blocking the calling thread.
So, when should you use
AddAsync? In general, an async method should use be used whenever you are working with an application that relies on asynchronous programming, such as a web application or a mobile app. This is because an async implementation allows your application to remain responsive while the database operation is being performed.
It's also worth noting that (here)
AddAsync is not always faster than
Add. In fact, in some cases,
AddAsync may actually be slower due to the overhead of starting and managing the asynchronous task. After all, the state machine costs performance in principle. However, the advantages outweigh the disadvantages in almost all cases.
Under the hood of Add and AddAsync
The special feature of
AddAsync is that there are additional features that are not obvious at first glance.
The fact that a method is offered as Async implies that a network call is made. But this is not the case with Add, is it? Yes, a network call can be made, namely when using certain value generators. The docs of AddAsync(Object, CancellationToken) Method says:
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.
In summary, the use of Async in this case is only recommended if the feature of value generators, which causes database network roundtips, is actively used. For all other cases, the non-asynchronous way via
Add should be used, as recommended by the documentation (current status).
In case of doubt, however,
AddAsync can be used here as well without any problems. Even if the feature of Value Generators is not used it is not worse than vice versa.