Many-to-one relation exception due to closed session after loading


I am using NHibernate (version 1.2.1) for the first time so I wrote a simple test application (an ASP.NET project) that uses it. In my database I have two tables: Persons and Categories. Each person gets one category, seems easy enough.

| Persons | | Categories | |--------------| |--------------| | Id (PK) | | Id (PK) | | Firstname | | CategoryName | | Lastname | | CreatedTime | | CategoryId | | UpdatedTime | | CreatedTime | | Deleted | | UpdatedTime | | Deleted |

The Id, CreatedTime, UpdatedTime and Deleted attributes are a convention I use in all my tables, so I have tried to bring this fact into an additional abstraction layer. I have a project DatabaseFramework which has three important classes:

<ul><li>Entity: an abstract class that defines these four properties. All 'entity objects' (in this case Person and Category) must inherit Entity.</li> <li>IEntityManager: a generic interface (type parameter as Entity) that defines methods like Load, Insert, Update, etc.</li> <li>NHibernateEntityManager: an implementation of this interface using NHibernate to do the loading, saving, etc. </li></ul>

Now, the Person and Category classes are straightforward, they just define the attributes of the tables of course (keeping in mind that four of them are in the base Entity class).<br /> Since the Persons table is related to the Categories table via the CategoryId attribute, the Person class has a Category property that holds the related category. However, in my webpage, I will also need the name of this category (CategoryName), for databinding purposes for example. So I created an additional property CategoryName that returns the CategoryName property of the current Category property, or an empty string if the Category is null:<br />

Namespace Database Public Class Person Inherits DatabaseFramework.Entity Public Overridable Property Firstname As String Public Overridable Property Lastname As String Public Overridable Property Category As Category Public Overridable ReadOnly Property CategoryName As String Get Return If(Me.Category Is Nothing, _ String.Empty, _ Me.Category.CategoryName) End Get End Property End Class

End Namespace

I am mapping the Person class using this mapping file. The many-to-one relation was suggested by Yads in another thread:<br />

<id name="Id" column="Id" type="int" unsaved-value="0"> <generator class="identity" /> </id> <property name="CreatedTime" type="DateTime" not-null="true" /> <property name="UpdatedTime" type="DateTime" not-null="true" /> <property name="Deleted" type="Boolean" not-null="true" /> <property name="Firstname" type="String" /> <property name="Lastname" type="String" /> <many-to-one name="Category" column="CategoryId" class="NHibernateWebTest.Database.Category, NHibernateWebTest" />

(I can't get it to show the root node, this forum hides it, I don't know how to escape the html-like tags...)

The final important detail is the Load method of the NHibernateEntityManager implementation. (This is in C# as it's in a different project, sorry about that).<br /> I simply open a new ISession (ISessionFactory.OpenSession) in the GetSession method and then use that to fill an EntityCollection(Of TEntity) which is just a collection inheriting System.Collections.ObjectModel.Collection(Of T).<br />

public virtual EntityCollection< TEntity > Load() { using (ISession session = this.GetSession()) { var entities = session .CreateCriteria(typeof (TEntity)) .Add(Expression.Eq("Deleted", false)) .List< TEntity >(); return new EntityCollection< TEntity >(entities); } } <br /> (Again, I can't get it to format the code correctly, it hides the generic type parameters, probably because it reads the angled symbols as a HTML tag..? If you know how to let me do that, let me know!)

Now, the idea of this Load method is that I get a fully functional collection of Persons, all their properties set to the correct values (including the Category property, and thus, the CategoryName property should return the correct name).<br /> However, it seems that is not the case. When I try to data-bind the result of this Load method to a GridView in ASP.NET, it tells me this:

Property accessor 'CategoryName' on object 'NHibernateWebTest.Database.Person' threw the following exception:'Could not initialize proxy - the owning Session was closed.'

The exception occurs on the DataBind method call here:

public virtual void LoadGrid() { if (this.Grid == null) return; this.Grid.DataSource = this.Manager.Load(); this.Grid.DataBind(); }

Well, of course the session is closed, I closed it via the using block. Isn't that the correct approach, should I keep the session open? And for how long? Can I close it after the DataBind method has been run?

In each case, I'd really like my Load method to just return a functional collection of items. It seems to me that it is now only getting the Category when it is required (eg, when the GridView wants to read the CategoryName, which wants to read the Category property), but at that time the session is closed. Is that reasoning correct?

How do I stop this behavior? Or shouldn't I? And what should I do otherwise?



Setting lazy loading = false in your mapping will solve the error. It would be a better practice though to tell NHibernate in your load query that you want to fetch the child collection of categories eagerly.

For a criteia query something like .SetFetchMode("Categories", FetchMode.Eager) should work.

Here is a <a href="http://ayende.com/Blog/archive/2006/05/02/CombatingTheSelectN1ProblemInNHibernate.aspx" rel="nofollow">link</a> that gives some insight into the so called "n + 1" problem, how lazy loading relates to it, and how NHibernate is meant to be used.

HTH,<br /> Berryl

something like this:

var entities = session .CreateCriteria<TEntity>() .SetFetchMode("Categories", FetchMode.Eager) .Add(Expression.Eq("Deleted", false)) .List< TEntity >();


The problem is that when your entity is lazy loaded. The query only gets the items that it currently needs. So in your case it gets the Person object. Then when you access any linked entities, it fires off another query. It uses proxy objects for this that know about the Session that was used. You are only keeping the Session open for the Load and then you're closing it.

This is actually bad practice in the NHibernate world. You want to keep the session alive for a period known as a <a href="http://nhforge.org/wikis/patternsandpractices/nhibernate-and-the-unit-of-work-pattern.aspx" rel="nofollow">unit of work</a>. This gives you a lot of benefits, like caching and lazy loading. Consequently you can disable lazy loading it should work. Although I'd recommend modifying your loader class if at all possiblem


  • How to edit a Word document that opens in read-mode in VBA
  • DependencyObject.AssociatedObject is always null
  • C++ Coin flip program error
  • string.IsNullOrEmpty() Doesn't Seem to Work on a String within a Class within a Class
  • WPF Template Binding in ToggleButton UserControl
  • How to getText() from the input field of an angularjs Application
  • Disable Kendo Autocomplete
  • Jackson Parser: ignore deserializing for type mismatch
  • How to use remove-erase idiom for removing empty vectors in a vector?
  • Repeat a vertical line on every page in Report Builder / SSRS
  • Why is an OPTIONS request sent to the server?
  • How to extract text from Word files using C#?
  • How to check if every primary key value is being referenced as foreign key in another table
  • Sending data from AppleScript to FileMaker records
  • How to set my toolbar fixed while scrolling android
  • Invalid access key error using credentials redeemed from an amazon open id token
  • AT Commands to Send SMS not working in Windows 8.1
  • Cannot Parse HTML Data Using Android / JSOUP
  • PHP: When would you need the self:: keyword?
  • Linker errors when using intrinsic function via function pointer
  • Windows forms listbox.selecteditem displaying “System.Data.DataRowView” instead of actual value
  • Acquiring multiple attributes from .xml file in c#
  • JTable with a ScrollPane misbehaving
  • Java static initializers and reflection
  • LevelDB C iterator
  • apache spark aggregate function using min value
  • unknown Exception android
  • Checking variable from a different class in C#
  • Django query for large number of relationships
  • Sorting a 2D array using the second column C++
  • How to get NHibernate ISession to cache entity not retrieved by primary key
  • reshape alternating columns in less time and using less memory
  • Why is Django giving me: 'first_name' is an invalid keyword argument for this function?
  • Observable and ngFor in Angular 2
  • How can i traverse a binary tree from right to left in java?
  • How can I use `wmic` in a Windows PE script?
  • failed to connect to specific WiFi in android programmatically
  • Unable to use reactive element in my shiny app
  • How to push additional view controllers onto NavigationController but keep the TabBar?
  • How can I use threading to 'tick' a timer to be accessed by other threads?