I am developing a website with ASP.NET MVC, NHibernate, and Fluent Hibernate and am getting a " session or session closed " error when trying to access a child.
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 cards:
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 Factory session 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 the database using this code:
IImageGalleryRepository igr = new ImageGalleryRepository(); ImageGallery ig = igr.GetById(1);
But when I try to access the child Image using this code
string imageFile = ig.Images[1].File;
I get this error:
Initialization [Entities.ImageGallery # 1] - failed to lazily initialize the role collection: Entities.ImageGallery.Images, session or session closed
Does anyone know how I can fix this?
Many thanks!
Edit
My GetById Method:
public ImageGallery GetById(int id) { using(ISession session = NHibernateSessionFactory.OpenSession()) { return session.Get<ImageGallery>(id); } }