Search code examples
c#entity-frameworkentity-framework-coretransactions

EF Core transactions


there is probably already a good answer to this topic somewhere, but would love if you could help. I don't understand the point of using explicit transactions in ef core, for example

ctx.Database.BeginTransaction();
...some chnages
ctx.SaveChangesAsync();
...osme changes
ctx.SaveChangesASync();
transaction.commit();

what was the problem with just writing

...some changes
ctx.SaveChangesAsync();

if it applies our changes as a transaction? I can see the use of explicit transactions, probably useful when working with different databases, but there is another question, how does IDBTransaction differ from TransactionScope? that it can work with different contexts?

Translated with DeepL.com (free version)

Want to know............


Solution

  • EF has an implicit transaction for each SaveChangesAsync call. Explicit transactions are rarely need, except you maybe need to call SaveChangesAsync multiple times, and want to roll back all of it for some reason.

    In that case, making your own IDBTransaction is more explicit. TransactionScope creates an "ambient transaction" for all your operations, which might be useful in some cases, but I rarely use that.

    In short: Don't use explicit transactions in EF. It's unlikely you'll need it, esp. when you're a beginner.