开发者

LazyInitializationException in ASP.NET app with NHibernate

Using NHibernate with ASP.NET 4.

I have had no issues retrieving objects, but I've just got to a point with nested objects that I can't figure out.

I am using lazy=true and when accessing a lazy-load collection I get the message:

Initializing[type#3]-failed to lazily initialize a collection of role: [type], no session or session was closed

Even if I call SessionFactory.OpenSession() immed开发者_运维技巧iately prior to the object being accessed, it makes no difference. I have also tried accessing the collection in a using ISession block to no luck.

Edit to add - I do have current_session_context_class = web set in web.config, and I am using CurrentSessionContext.Bind on BeginRequest.

Can anyone offer some advice?

Not an MVC app

I read this - don't know how accurate it is, and it is Hibernate: http://opensource.atlassian.com/projects/hibernate/browse/HHH-2878

It says something about a bug in many-to-many relationships.

Here is my HBM mapping:

<bag name="Objects" table="ObjectInstance" cascade="all" lazy="true">
  <key column="branchId" />
  <many-to-many class="InventoryObjectInstance" column="objectInstanceId" />
</bag>


Does that happen after you perform some save/update operations? Where and when are you closing the session? To me, it sounds like you close the session right after save call or in some other method before the web page gets rendered. In other words, make sure you are using Open Session in View pattern and close the session only in the end of current web-request. You can also check out this post.


When object graphs are retrieved they keep a reference to the session that spawned them. They use that session for lazy loading of their properties. If the original session is closed, you will get this error (or one just like it) when trying to access them. Opening a new session will not help.

You can try to find where the original request session is being closed and stop that. Are you in the same request though? Failing that you can try to connect your object to a new session -- I think it is Session.Lock(YourObject). Alternatively you could retrieve the object again from the new session.


For some reason you are getting a new ISession when you call SessionFactory.OpenSession(). Is your first use of the session wrapping access to it in a using block? Why are you calling OpenSession again anyway -- what happened to the reference to the session?

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜