I'm newbie to C#. I want to add transaction support to the following code, but I'm confused on whether its already using transaction or not since we have a call to commitAsync. Plus its not using SaveChangesAsync, dont we need this?. Is it enough to call the crud methods and do a commit without savechanges?
public async Task<Unit> Handle(UserCommand command, CancellationToken token)
{
var user = _mapper.Map<User>(command);
_context.User.Add(user)
await _context.CommitAsync();
return Unit.Value;
}
Here is what I have at hand, is this ok or is there a better way to do this?
public async Task<Unit> Handle(UserCommand command, CancellationToken token)
{
using var transaction = _context.Database.BeginTransaction();
try {
// adding, removing, updating...
var user = _mapper.Map<User>(command);
await _context.User.AddAsync(user)
await _context.SaveChangesAsync(token); //can we skip this stmt and jump to commit?
await transaction.CommitAsync();
}
catch {
await transaction.RollbackAsync(); //do I need this or this automatically handled on fail?
throw;
}
return Unit.Value;
}
One more question is it better to use sync or async version of BeginTransaction in this case? FYI, the async version doesnt contain Commit and RollbackAsync functions, do we have equivalent methods for these for async.