开发者

NHibernate - Many To One - NHibernate.LazyInitializationException - Could not initialize proxy

I am getting this exception when I attempt to access an object that is stored in a property of my domain object. I have done some research and still do not understand why I am getting this error.

I have a very basic repository in which I am creating a session and then using a ICriteria query to fetch the first record from the list of results. My Connection domain object has one to many relationship mapped to Server. Why does the session not include the server as a proxy when it fetches the Connection object? I'm not very familiar session managment with NHibernate.

Here is my implementation:

Domain obj:

public class Connection {

public virtual int Id { get; private set; }


public virtual string FullName { get; set; }


public virtual string Email { get; set; }


public virtual string NickName { get; set; }


public virtual string Alternative { get; set; }


public virtual bool IsInvisible { get; set; }


public virtual Server CurrentServer { get; set; }

}

  public Connection GetConnection()
    {
        using (ISession session = NHibernateHelpe开发者_JAVA百科r.OpenSession())
        {
            ICriteria crit = session.CreateCriteria(typeof(Connection));
            crit.SetMaxResults(1);
            IList<Connection> connection = crit.List<Connection>();
            return connection[0];

        }
    }

The above will successfully return a Connection object. However accessing the CurrentServer property with throw the exception. It is/was my assumption that NHibernate was aware of the relationship that this object has with 'CurrentServer' and would therefore load that object, lazily, when requested. Can someone tell me where I was led astray?

Thanks!


You dispose the session first, and start the lazy loading after that. An object should be connected to a session to enable lazy loading.


I found the answer due to Jamie Ide's comment. The problem was that I was wrapping my session in a using statement. That meant that when I attempted to access the Server property the current session had already been disposed and therefore the lazy loading could not use that session to fetch the server.


If it's a web app., use the session-per-request pattern. If it's a Windows app. it will take more work. I hold a session open for the lifetime of a Windows Form and dispose it in the FormClosing event. This works great for all but a few cases.

What won't I do for 15 points? :-)

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜