0

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);
                }
            }
        }
} 
cbp
  • 25,252
  • 29
  • 125
  • 205

1 Answers1

2

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

Community
  • 1
  • 1
cmsjr
  • 56,771
  • 11
  • 70
  • 62
  • 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 Oct 19 '09 at 01:34
  • 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 Oct 19 '09 at 02:13
  • also, maybe check this out check this out http://ayende.com/Blog/archive/2006/06/04/NHibernateAndSystemTransactionsASuccess.aspx – cmsjr Oct 19 '09 at 02:14
  • Thanks. Wrapping sessions in transactions conflicts with the common Session-Per-Web-Request method though. Urg... what a nightmare – cbp Oct 20 '09 at 00:01
  • Same problem as this guy I think: http://stackoverflow.com/questions/1518855/nhibernate-transactions-and-transactionscope – cbp Oct 20 '09 at 00:11