开发者

don't flush the Session after an exception occurs

开发者 https://www.devze.com 2023-02-20 01:52 出处:网络
NHibernateSessionManager.Instance.GetSessionFrom(SessionFactoryConfigPath).Flush(); i get null id in FoodOrder.Core.Entities.Articles entry (don\'t flush the Session after an exception occurs)
NHibernateSessionManager.Instance.GetSessionFrom(SessionFactoryConfigPath).Flush();

i get

null id in FoodOrder.Core.Entities.Articles entry (don't flush the Session after an exception occurs)

can i just use try catch and session.Close or what is better to do in this example?

example

public void CommitChanges()
        {
            if (NHibernateSessionManager.Instance.HasOpenTransactionOn(SessionFactoryConfigPath))
            {
                NHibernateSessionManager.Instance.CommitTransactionOn(SessionFactoryConfigP开发者_开发知识库ath);
            }
            else
            {
                try
                {
                    // If there's no transaction, just flush the changes
                    NHibernateSessionManager.Instance.GetSessionFrom(SessionFactoryConfigPath).Flush();
                }
                finally
                {
                    NHibernateSessionManager.Instance.GetSessionFrom(SessionFactoryConfigPath).Close();
                }
            }
        }


After an exception, your session is in an invalid state and should just be disposed. This is one reason why you should always perform writes in a transaction. If not, you have no idea as to the state of your database. So I would recommend that:

  1. You don't explicitly flush and always insist that data access (reads and writes) are done inside a transaction.
  2. If that's not an option, I would encourage you to find the root cause of the exception - sounds like you have an entity mapped with an assigned id that was never set - and fix that.
  3. If that's not an option, then dispose of the session when an exception occurs.

Hope that helps.

0

精彩评论

暂无评论...
验证码 换一张
取 消