Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework - SaveChanges vs Transaction

I have a bit stupid question, but I didn't find an answer.

Is there any difference between a single call to SaveChanges() and a single call to SaveChanges() inside a transaction? (I'm using Entity Framework in .net core 5 application)

I want to create a record in one table and update data in another one.

For example, it would be:

users.Password = "..."

var passwordReset = new PasswordReset(...)

_context.Add(passwordReset);
_context.SaveChanges();

And with transaction:

using (var transaction = _context.Database.BeginTransaction())
{
    users.Password = "..."

    var passwordReset = new PasswordReset(...)

    _context.Add(passwordReset);
    _context.SaveChanges();

    transaction.Commit();
}

I want to ensure, that two queries will complete successfully but I don't know which option would be the best for me.

Thanks in advance

like image 381
Jarosław Leśniak Avatar asked Jun 25 '26 03:06

Jarosław Leśniak


1 Answers

Is [there] any difference between single call [to] SaveChanges() and [a] single call [to] SaveChanges() inside a transaction? (I'm using Entity Framework in .net core 5 application)

Not really. A single call to SaveChanges() forms its own transaction. Using a transaction is a way to group multiple calls to SaveChanges together so they may all succeed or all fail (or have finer grained control to partly rollback on failure).

See the reference on transactions in EF Core

like image 83
AndyG Avatar answered Jun 26 '26 15:06

AndyG



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!