简体   繁体   中英

NHibernate Race Condition on two statements in one transaction

I have been trying to execute below codes in one transaction but it seems that order of execution is not in order.

 var UpdateQuery = ""; // Some update query

 session.Transaction.Begin();


// Start of Statement 1
    var orders = session.Query<Order>().ToList();
                foreach (var order in orders)
                {
                    order.IsDeleted = true;
                    session.Update(order);
                }
// End of Statement 1

// Start of Statement 2

     var query = session.CreateSQLQuery(UpdateQuery)
                .SetInt32("UserId", userId);

     query.ExecuteUpdate();

// End of Statement 2

 session.Transaction.Commit();

The weird thing is that even though Query is in the first statement. CreateSQLQuery is still executed first in the NHibernate Profiler. It Should execute the Query in statement 1 to update the IsDeleted property first. I'm not sure what am I missing.

When working with session, we in fact work with an abstract layer. That does not sync itself with DB all the time. It is done wisely. Read more about it here:

http://nhibernate.info/doc/nh/en/index.html#manipulatingdata-flushing

To fix the issue, we need to execute sync ... FLUSH

session.Transaction.Begin();

// Start of Statement 1
...
// End of Statement 1

session.Flush(); // this will cause the SYNC of all updates 

// Start of Statement 2
...
// End of Statement 2

session.Transaction.Commit();

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