I am getting Nhibernate Session closed exception with asp.net mvc telerik ajax grid. The grid is bound to an entity Sale that has a related entity User. The exception thrown is when trying to access the User entity. I have used the fetchMode to eager load it but I still get the same exception. This exception only occur if I switch between the grid pages multiple times. Anyone encountered this issue?
The code for that data access is as follow:
public IList<Sale> List()
{
var manager = new ManagerFactory().GetSaleManager();
var iCriteria = manager.Session.GetISession().CreateCriteria(typeof(Sale))
.SetFetchMode("AspnetUser3.Agents3", FetchMode.Eager);
return iCriteria.List<Sale>();
}
The code that try to access the related object in the object graph is as follow:
AgentId = sale.AspnetUser3.Agents3[0].Id,
The exception thrown
NHibernate.Exceptions.GenericADOException: could not load an entity: [SalesEntry.Data.Model.AspnetUser#7aaabf99-d77d-4edf-b949-9c4c0f3e85d8][SQL: SELECT aspnetuser0_.[UserId] as column1_12_0_, aspnetuser0_.[UserName] as column2_12_0_, aspnetuser0_.[LoweredUserName] as column3_12_0_, aspnetuser0_.[MobileAlias] as column4_12_0_, aspnetuser0_.[IsAnonymous] as column5_12_0_, aspnetuser0_.[LastActivityDate] as column6_12_0_, aspnetuser0_.[ApplicationId] as column7_12_0_ FROM [dbo].[aspnet_Users] aspnetuser0_ WHERE aspnetuser0_.[UserId]=?] ---> System.ObjectDisposedException: Session is closed!
Object name: 'ISession'.
It’s happening because User is being lazy loaded and you’re likely seeing a situation where the session is being closed before the User object is loaded. Then when the Grid accesses the User reference you get this exception. Make sure you’re following the Unit of Work pattern.
Also you may want to use a Model class to bind to your grid, rather than the entity directly. That way you control what kind of access is done and you avoid having unexpected changes to your entities/database.