2012-02-08 72 views
0

已经使用NHibernate很长时间了,我现在正在学习实体框架。在NHibernate中,对于每个ISession实例,我使用ISession.BeginTransaction实例化单个数据库事务。在实体框架中,我将如何实现每个上下文一次事务的相同效果?实体框架与NHibernate交易

回答

0

ISession并不严格对应于nHibernate中的数据库事务,但它确实具有内置的隐式事务,您可以在此处看到更多:NHProf about implicit transactions

在实体框架,当你调用的SaveChanges交易开始隐式的,你可以阅读更多关于在this article on msdn

要在实体框架您使用的TransactionScope的BeginTransaction或在EntityConnection明确的事务。

最简单的方法是使用TransactionScope的是这样的:

using (TransactionScope tran = new TransactionScope()){ 
    context.SaveChanges(); 
    //Do more work with this or another context 
    context.SaveChanges(); 
    tran.Complete(); 
    //Or alternatively don't call Complete and because of the using block Dispose on tran will be 
    //called causing an Rollback 
} 
+0

我检查了我的代码,你说得对NHibernate的,所以我澄清我的问题。请提供一些关于EF的示例代码。 – HappyNomad 2012-02-08 09:28:27

+0

我修改了我的答案,以包含使用TransactionScope的示例 – jakobandersen 2012-02-08 19:28:08