Sql事务的替代方案,实体框架中的回滚 [英] Alternative of Sql transactions, roll-back in entity framwork

查看:83
本文介绍了Sql事务的替代方案,实体框架中的回滚的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述





我的数据库中有一些表,并希望使用中的实体框架在这些表中插入记录MVC 4.0

以这种方式插入,子表中的记录插入取决于主表中的记录。

此功能可以实现在sql server中轻松通过 Transaction和roll-back 。如果记录无法插入到流程中涉及的任何表中,那么整个插入过程将会回滚。



我想要替代此使用MVC 4.0中的实体框架进行交易和回滚



请提供一些建议。



谢谢,



问候,

Ashish

Hi,

I have some tables in my database and want to insert records in these tables using Entity framework in MVC 4.0.
Insertion took place in this way that insertion of record in child table depends on the records in the master table.
This functionality could be achieve easily by Transaction and roll-back in the sql server. Where If record could not be insert in any of the table involved in the process then whole insertion process would roll-backed.

I want the alternative of this Transaction and roll-back with Entity framework in MVC 4.0.

Please provide some suggestions.

Thank you,

Regards,
Ashish

推荐答案

使用交易你可以解决你的问题



Using Transactions you can solve your problms

using System.Transactions; /Inculde this Directory and Reference


using (TransactionScope trans = new TransactionScope())
            {
                try
                {

                    using (DBEntities en = new DBEntities())
                    {
                        /*


			Yours DML(S)



			*/
		    }


                    trans.Complete();//If Success

                    
                }

                catch (Exception ex)
                {
                    trans.Dispose();//If Not Success
                    
                }
}


从字面上看,Google为实体框架交易提供的第一个结果:

Literally the first result from Google for "Entity Framework Transaction":


在所有版本的Entity Framework中,每当执行 SaveChanges()以在数据库上插入,更新或删除时,框架都会将该操作包装在事务中。此事务仅持续足够长的时间来执行操作然后完成。当您执行另一个此类操作时,将启动一个新事务。


In all versions of Entity Framework, whenever you execute SaveChanges() to insert, update or delete on the database the framework will wrap that operation in a transaction. This transaction lasts only long enough to execute the operation and then completes. When you execute another such operation a new transaction is started.


这篇关于Sql事务的替代方案,实体框架中的回滚的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆