How to fix a NHibernate lazy loading error "no session or session was closed"?
Posted
by MCardinale
on Stack Overflow
See other posts from Stack Overflow
or by MCardinale
Published on 2010-03-25T22:41:31Z
Indexed on
2010/03/25
22:43 UTC
Read the original article
Hit count: 955
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!
© Stack Overflow or respective owner