AddAsync() vs Add() in EF Core

asp.net-core entity-framework-core

Question

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?

1
20
11/6/2017 10:54:07 AM

Popular Answer

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() and Add() 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?

  • If you're not writing async code, then definitely use Add().
  • If you're writing async code and want to keep things simple, choose AddAsync() just as you would for other methods.
  • If you really want to avoid the overhead of async calls and you know 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.

23
9/13/2018 5:17:58 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow