views:

137

answers:

1

The following code demonstrates a misleading situation in which data is committed to the database, even though commit is never called on a transaction.

Could anyone explain why?

[TestFixture]
public class TestFixture
{
        [Test]
        public void Test()
        {
            var config = DoConfiguration();

            using(var factory = config.BuildSessionFactory())
            {
                using (var session = factory.OpenSession())
                {
                    CallSessionContext.Bind(session);

                    using(new TransactionScope())
                    {
                        using (session.BeginTransaction())
                        {
                            var myEntity = session
                               .CreateQuery("from myEntity")
                               .List<MyEntity>()[0];

                            myEntity.Name = "test name";
                        }

                        var myEntity2 = session
                           .CreateQuery("from myEntity")
                           .List<MyEntity>()[0];

                        myEntity2.Name = "test name";

                        session.Flush();
                    }

                    CallSessionContext.Unbind(factory);
                }
            }
        }
}
+2  A: 

Explicitly calling session.flush() is persisting your changes. Discussed in detail in this post

cmsjr
Hi thanks, So I guess the question is - Is there any way of running two NHibernate transactions within the same TransactionScope, without killing the TransactionScope in between?
cbp
I'm not familiar enough to say with confidence, but I would suspect you should wrap your session usage with the transaction scope, rather than creating nHibernate transactions on a session declared outside of the transaction scope.
cmsjr
also, maybe check this out check this outhttp://ayende.com/Blog/archive/2006/06/04/NHibernateAndSystemTransactionsASuccess.aspx
cmsjr
Thanks. Wrapping sessions in transactions conflicts with the common Session-Per-Web-Request method though. Urg... what a nightmare
cbp
Same problem as this guy I think: http://stackoverflow.com/questions/1518855/nhibernate-transactions-and-transactionscope
cbp