开发者

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

开发者 https://www.devze.com 2023-03-06 23:57 出处:网络
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.

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.

  • an EDMX for Invoics: Invoice table, InvoiceDetails, Customer
  • an EDMX for Orders: Order table, OrderDetails, Customer
  • etc.

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 Se开发者_JAVA技巧rviceLocator 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


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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消