Mastenka
Mastenka

Reputation: 345

Context AddAsync + SaveChangesAsync => Double await?

What do you think about using async + await two times in a row when using EF Core in WEB-API .NET Core webapp?

await _context.Teams.AddAsync(newTeam);
await _context.SaveChangesAsync();

return newTeam.TeamId;

Does it makes sense? I want code of creating new Team to be async safe. But should I use "AddAsync + SaveChangesAsync" or is the "Add + SaveChangesAsync" safe as well?

What do you think? Thanks a lot!

Upvotes: 3

Views: 4551

Answers (1)

citronas
citronas

Reputation: 19365

Yes, you can use both. Please pass the CancellationToken from the controller down to both methods, so you that you have

await _context.Teams.AddAsync(newTeam, ct);
await _context.SaveChangesAsync(ct);

https://learn.microsoft.com/en-us/dotnet/api/microsoft.entityframeworkcore.dbcontext.addasync?view=efcore-6.0

This way, you can save calculation time if the request is aborted.

Upvotes: 3

Related Questions