bzamfir
bzamfir

Reputation: 4906

EF4 - How to "attach" entities from different ObjectContext's together, to save them all in the same transaction?

I want to create the app modular and would like to create multiple EDMX, with just the subset to tables needed in that specific context.

E.g.

This way I keep things smaller and manageable (I think)

But I might need to create a generic module that performs a batch operation on several entities, possible spread across multiple EDMX. E.g. Consolidate clients - merge multiple clients to a single client (maybe users entered same client by mistake multiple times, or I want to merge two client accounts,etc)

For this I want to use ServiceLocator pattern

  1. define an interface, IClientMerger
  2. and as I create a new entity that refer to client, I also create a new IClientMerger handler
  3. when I need to deduplicate, I load all ICLientHandlers, and call them in a loop, and they replace the old ClientID with new ClientID in handled entity (one in Invoices, one in Orders, etc.)

All is fine, but I want to pack this all in a transaction, so all will get saved or not. being in separate EDMX, how can I pack them all in a single transaction? Should I manually create a ADO.NET transaction and call objectContext.SaveChanges for all EDMX inside? Or there's another, more elegant way?

Thanks

Upvotes: 0

Views: 328

Answers (2)

Guillaume Davion
Guillaume Davion

Reputation: 434

using(TransactionScope tran = new TransactionScope())
{
  //do some work...
  context1.SaveChanges()
  context2.SaveChanges()

  tran.Commit()
}

If there's no Commit before the TransactionScope is disposed, the transaction is automatically rollbacked.

The contexts can even work on differents sql servers if MS DTC is available.

Upvotes: 1

Devart
Devart

Reputation: 122042

Try the TransactionScope class.
You will need the Required TransactonScopeOption.

Upvotes: 0

Related Questions