简体   繁体   中英

Question about Entity Framework and Transactions

        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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM