如何修复NHibernate的延迟加载错误"没有会话或会话关闭"? [英] How to fix a NHibernate lazy loading error "no session or session was closed"?

查看:172
本文介绍了如何修复NHibernate的延迟加载错误"没有会话或会话关闭"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发展与ASP.NET MVC,NHibernate和流利的Hibernate的一个网站,并得到错误没有会话或会话关闭当我试图访问一个子对象。

这是我的域名类别:

 公共类ImageGallery {
    公共虚拟INT标识{搞定;组; }
    公共虚拟字符串名称{搞定;组; }
    公共虚拟的IList<图像>图片{搞定;组; }
}公共类图片{
    公共虚拟INT标识{搞定;组; }
    公共虚拟ImageGallery ImageGallery {搞定;组; }
    公共虚拟字符串的文件{搞定;组; }
}

这是我的地图:

 公共类ImageGalleryMap:ClassMap< ImageGallery> {
    公共ImageGalleryMap(){
        ID(X => x.Id);
        地图(X => x.Title);
        的hasMany(X => x.Images);
    }
}公共类图像映射:ClassMap<图像> {
    公共图像映射(){
        ID(X => x.Id);
        参考文献(X => x.ImageGallery);
        地图(X => x.File);
    }
}

这是我的会话工厂辅助类:

 公共类NHibernateSessionFactory {
    私有静态ISessionFactory _sessionFactory;
    私有静态ISessionFactory的SessionFactory {
        获得{
            如果(_sessionFactory == NULL){
                _sessionFactory = Fluently.Configure()
                    .Database(MySQLConfiguration.Standard.ConnectionString(MyConnString))
                    .Mappings(M = GT; m.FluentMappings.AddFromAssemblyOf< ImageGalleryMap>())
                    .ExposeConfiguration(C => c.Properties.Add(hbm2ddl.keywords,无))
                    .BuildSessionFactory();
            }
            返回_sessionFactory;
        }
    }
    公共静态的ISession的openSession(){
        返回SessionFactory.OpenSession();
    }
}

一切工作正常,当我用这个code得到的 ImageGallery 从数据库:

  IImageGalleryRepository IGR =新ImageGalleryRepository();
ImageGallery IG = igr.GetById(1);

但是,当我尝试访问图片此code子对象

 字符串镜像文件= ig.Images [1] .File;

我得到这个错误:

初始化[Entities.ImageGallery#1] -failed懒洋洋地初始化角色的集合:Entities.ImageGallery.Images,没有会话或会话关闭

有人知道我是怎么解决这个问题?

非常感谢你!

修改

我GetById方法是:

 公共ImageGallery GetById(INT ID){
        使用(ISession的会话= NHibernateSessionFactory.OpenSession()){
            返回session.Get&所述; ImageGallery>(ID);
        }
    }


解决方案

presumably,你的 GetById 正在关闭会话。这可能是明确的,或通过using语句。

会话管理一个更好的方法是打开会话视图中的的模式。 NHibernate的会话是便宜的创建,所以在各请求的开始创建一个,并在最后将其关闭。

 中的global.asax.cs //公共无效的Application_Start()
{
    的BeginRequest + = {委托
        CurrentSessionContext.Bind(sessionFactory.OpenSession());
    };    EndRequest + = {委托
        VAR会话= SessionFactory.getCurrentSession()函数;
        如果(空!=会话){
            session.Dispose();
        }
        CurrentSessionContext.Unbind(SessionFactory的);
    };
}//你NHibernateSessionFactory类
公共静态的ISession的openSession(){
    返回SessionFactory.getCurrentSession()函数;
}

使用DI容器,我们可以有每个请求的范围的情况下,注入了会议。

  // ninject例子
绑定<&ISession的GT;()
    .ToMethod(CTX => SessionFactory.getCurrentSession()函数)
    .InRequestScope();

I'm developing a website with ASP.NET MVC, NHibernate and Fluent Hibernate and getting the error "no session or session was closed" when I try to access a child object.

These are my domain classes:

public class ImageGallery {
    public virtual int Id { get; set; }
    public virtual string Title { get; set; }
    public virtual IList<Image> Images { get; set; }
}

public class Image {
    public virtual int Id { get; set; }
    public virtual ImageGallery ImageGallery { get; set; }
    public virtual string File { get; set; }
}

These are my maps:

public class ImageGalleryMap:ClassMap<ImageGallery> {
    public ImageGalleryMap() {
        Id(x => x.Id);
        Map(x => x.Title);
        HasMany(x => x.Images);
    }
}

public class ImageMap:ClassMap<Image> {
    public ImageMap() {
        Id(x => x.Id);
        References(x => x.ImageGallery);
        Map(x => x.File);
    }
}

And this is my Session Factory helper class:

public class NHibernateSessionFactory {
    private static ISessionFactory _sessionFactory;
    private static ISessionFactory SessionFactory {
        get {
            if(_sessionFactory == null) {
                _sessionFactory = Fluently.Configure()
                    .Database(MySQLConfiguration.Standard.ConnectionString(MyConnString))
                    .Mappings(m => m.FluentMappings.AddFromAssemblyOf<ImageGalleryMap>())
                    .ExposeConfiguration(c => c.Properties.Add("hbm2ddl.keywords", "none"))
                    .BuildSessionFactory();
            }
            return _sessionFactory;
        }
    }
    public static ISession OpenSession() {
        return SessionFactory.OpenSession();
    }
}

Everything works fine, when I get ImageGallery from database using this code:

IImageGalleryRepository igr = new ImageGalleryRepository();
ImageGallery ig = igr.GetById(1);

But, when I try to access the Image child object with this code

string imageFile = ig.Images[1].File;

I get this error:

Initializing[Entities.ImageGallery#1]-failed to lazily initialize a collection of role: Entities.ImageGallery.Images, no session or session was closed

Someone know how can I fix this?

Thank you very much!

Edit

My GetById method is:

    public ImageGallery GetById(int id) {
        using(ISession session = NHibernateSessionFactory.OpenSession()) {
            return session.Get<ImageGallery>(id);
        }
    }

解决方案

Presumably, your GetById is closing the session. This could be explicit, or via a using statement.

A better approach to session management is the Open Session in View pattern. NHibernate sessions are cheap to create, so create one at the start of each request, and close it at the end.

// in global.asax.cs

public void Application_Start()
{
    BeginRequest += delegate {
        CurrentSessionContext.Bind( sessionFactory.OpenSession());
    };

    EndRequest += delegate {
        var session = sessionFactory.GetCurrentSession();
        if (null != session) {
            session.Dispose();
        }
        CurrentSessionContext.Unbind(sessionFactory);
    };
}

// in your NHibernateSessionFactory class
public static ISession OpenSession() {
    return SessionFactory.GetCurrentSession();
}

Using a DI container, we can have the session injected with instances scoped per-request.

// ninject example
Bind<ISession>()
    .ToMethod( ctx => sessionFactory.GetCurrentSession() )
    .InRequestScope();

这篇关于如何修复NHibernate的延迟加载错误&QUOT;没有会话或会话关闭&QUOT;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆