Nhibernate Lazy Load exception after a view exception

前端 未结 2 1585
执念已碎
执念已碎 2021-01-21 21:35

I get a weird behavior with NHibernate with Fluent Configuration.

Whenever a generic exception unrelated to the NHibernate occurs i.e. in the view a DivideByZeroEx

相关标签:
2条回答
  • 2021-01-21 22:04

    The extended question and all the snippets - are finally helping to find out where is the issue.

    There is a really big issue: Session["User"] = LoggedUser;

    This would hardly work. Why?

    • because we place into long running object (Web Session)
    • an instance loaded via very shortly lasting Web Request

    Not all its properties will/could be loaded, When we place LoggedUser into session. It could be just a root entity with many proxies representing references and collections. These will NEVER be loaded later, because its Mather session is closed... gone

    Solution?

    I would use .Clone() of the User object. In its implementation we can explicitly load all needed references and collections and clone them as well. Such object could be placed into the Web Session

    [Serializable]
    public class User, ICloneable, ...
    {
        ...
        public override object Clone()
        {
            var entity = base.Clone() as User;
            entity.Role = Role.Clone() as Role;
            ...
            return entity;
        }
    

    So, what would be placed into session?

    Session["User"] = LoggedUser.Clone();
    
    0 讨论(0)
  • 2021-01-21 22:20

    As Radim Köhler noted i was saving a lazy-loaded object in Session that caused the problem.

    But i wanted to avoid the Serilization of all objects and i fixed it as follows.

    I added the following method to eager-load an entity instead of lazy

    public T FindByEager(int id)
        {
            T entity = FindBy(id);
            NHibernateUtil.Initialize(entity);
            return entity;
        }
    

    And changed BaseController to

    if (Session != null) Session["User"] = userRepository.FindByEager(LoggedUser.Id);
    
    0 讨论(0)
提交回复
热议问题