1

I would like to know what's the best way to save multiple objects in a way that if the second 'obj.Insert()' throw a exception, all the changes rollback.

I a'm trying something like that:

Product product1 = new Product();
Product product2 = new Product();
Product product3 = new Product();

DbContext DB = new DB();

IProductInsert repository = new ProductInsert(DB);

repository.Insert(product1);
repository.Insert(product2);
repository.Insert(product3);

DB.SaveChanges();

But it is in my view, I think it's not correct..

How can I save all the changes or rollback using the DB.SaveChanges() in my repository classes?

MuriloKunze
  • 15,195
  • 17
  • 54
  • 82

1 Answers1

1

You should be able to do it with a transaction scope:

using (var ts = new TransactionScope()) {
    repository.Insert(product1);
    repository.Insert(product2);
    repository.Insert(product3);
    DB.SaveChanges();
    ts.Complete();
}

If anything fails in this sequence, and the call ts.Complete() is not reached, the background transaction is rolled back.

For a solution that works across multiple db contexts, see this answer.

Community
  • 1
  • 1
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523