Ok multiple questions here:
I am trying to understand what is the difference (outside the obvious asynchronous) between AddAsync()
and Add()
methods in EF Core?
When do you choose one over the other?
Does it matter if you choose one over the other for consistency?
AddAsync(Object, CancellationToken) Begins tracking the given entity, and any other reachable entities that are not already being tracked, in the Added state such that they will be inserted into the database when SaveChanges() is called. Use State to set the state of only a single entity.
UseHiLo(PropertyBuilder, String, String) Configures the key property to use a sequence-based hi-lo pattern to generate values for new entities, when targeting SQL Server. This method sets the property to be OnAdd.
You can use EF Core in APIs and applications that require the full . NET Framework, as well as those that target only the cross-platform .
Reverse engineering is the process of scaffolding entity type classes and a DbContext class based on a database schema. It can be performed using the Scaffold-DbContext command of the EF Core Package Manager Console (PMC) tools or the dotnet ef dbcontext scaffold command of the . NET Command-line Interface (CLI) tools.
After going through the code I agree with Henk Holterman's comment that using Add()
when your code is async is an optimization. The documentation for AddAsync()
is a little misleading when it says, "For all other cases the non async method should be used".
I am trying to understand what is the difference (outside the obvious asynchronous) between
AddAsync()
andAdd()
methods in EF Core?
AddAsync()
is 100% async safe, while Add()
is only async safe in certain conditions. Like the comment implies, one of your columns may be configured such that Entity Framework makes a query to the database to generate the value that will eventually be inserted. In that case, blocking would occur if you called Add()
.
When do you choose one over the other?
Add()
.AddAsync()
just as you would for other methods.Add()
will never make a database query, then use Add()
.Does it matter if you choose one over the other for consistency?
No, despite the recommendation in the AddAsync()
documentation.
From the source code:
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.
So if you use a value generator that might need to access the DB to get new values to assign to new entries, such as the SequenceHiLo generator, then use AddAsync()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With