I'm using Entity Framework 6 and .Net Framework 4.8 in a MVC application. I'm trying to do two things to a list of entities (invoices):
- Generate an email and send it.
- Update the entity and save it.
When the email fails to send, I want to roll back all changes I made to the entity.
This is my code:
foreach (var id in listOfIds)
{
using (var dbContextTransaction = db.Database.BeginTransaction())
{
try
{
var invoice = db.Invoices.Find(id);
MakeChangesToInvoice(invoice);
var pdf = GeneratePdf(invoice);
SendEmail(pdf);
db.SaveChanges();
dbContextTransaction.Commit();
}
catch(SomeEmailException)
{
dbContextTransaction.Rollback();
}
}
}
The problem here is that when I have a succesfull iteration AFTER a faulty iteration, the changes of the faulty iteration (that called Rollback) still get saved.