我正在使用asp.net mvc telerik ajax grid获得Nhibernate Session关闭异常。网格绑定到具有相关实体User的实体Sale。抛出的异常是尝试访问User实体时。我已经使用fetchMode来急切加载它,但我仍然得到相同的异常。仅当我多次在网格页面之间切换时才会出现此异常。有人遇到过这个问题吗?
该数据访问的代码如下:
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>();
}
尝试访问对象图中相关对象的代码如下:
AgentId = sale.AspnetUser3.Agents3[0].Id,
抛出异常
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'.
答案 0 :(得分:2)
这种情况正在发生,因为用户正在加载延迟,并且您可能会在加载User对象之前看到会话正在关闭的情况。然后当Grid访问User引用时,您会收到此异常。确保您关注Unit of Work pattern。
此外,您可能希望使用Model类绑定到网格,而不是直接绑定到实体。这样您就可以控制执行何种访问,并避免对实体/数据库进行意外更改。