views:

24

answers:

2
        public void SomeMethod1()
        {
            using (TemplateEntities ctx = new TemplateEntities())
            {
                //do something in this ctx
            }
        }

        public void SomeMethod2()
        {
            using (TemplateEntities ctx = new TemplateEntities())
            {
                //do something else in this ctx
            }
        }

        public void SomeMethod()
        {
            using (TemplateEntities ctx = new TemplateEntities())
            {
                using (TransactionScope tran = new TransactionScope())
                {
                    SomeMethod1();
                    SomeMethod2();
                    var itemToDelete= (from x in ctx.Xxx
                                    where x.Id==1
                                    select x).Single();
                    ctx.Xxx.DeleteObject(itemToDelete);
                    ctx.SaveChanges();
                    tran.Complete(); 
                }
            }
        }

What happens in SomeMethod is executed in a transaction even if there are more contexts? I am using POCO.

A: 

If you use TransactionScope with multiple ObjectContext instances the transaction will be promoted to distributed and whole operation (SomeMethod) will be handled still as atomic. But distributed transaction requires additional NT service and its dependecies. The service is called Microsoft Distributed Transaction Coordinator (MSDTC). This service has to run on all involved servers (application server and database server). In network scenario service requires some additional configuration. For communication RPC ports have to be opened in firewalls.

Ladislav Mrnka
But if we are talking about tables withing one database it's correct my example?
gigi
Nope, it will still require MSDTC. However, when you manage your own connection, this will not be a problem. See http://social.msdn.microsoft.com/Forums/en-US/adodotnetentityframework/thread/189b2718-c2b0-4290-8517-3cd3da4314fc for more information.
Pieter
A: 

Ultimately the database doesn't know about data-contexts, so simply: the rules of transactions apply. Being a serializable transaction, things like read locks and key-range-locks will be issued and honoured. As always, there is a risk of complication from deadlocks, but ultimately it should work. Note that all the contexts involved should enlist as required.

Marc Gravell