Nhibernate Lazy Load exception after a view exception

前端 未结 2 1619
执念已碎
执念已碎 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();
    

提交回复
热议问题