Search code examples
.netentity-frameworktransactionscopetask-parallel-libraryasync-ctp

EF4, TransactionScope and Task<>


Is it possible to open a TransactionScope, run a load of async Tasks which operate on an EF4 ObjectContext, and then commit the result?

How is the current transaction scope inferred in EF4? Will this fail if/when a task gets scheduled on a different thread to the transaction scope?


Solution

  • Yes, it is. For starters, Entity Framework just uses a provider underneath (by default System.Data.SqlClient) which will pick up the "ambient" transaction context from the thread that is executing. So, from there, the only trick is propagating the single transaction to the Tasks you spin up. I have explained how you can do that here in this post.

    While that post was more about propgating to PLINQ spawned tasks, the same approach is applicable if you're manually spinning up your own Tasks. If you would like a code sample, please give me basic details of exactly how your Task spawning would work so I can give good example code.