I've run into a truly frustrating problem and spent several hours trying every which way to sort out. When a collection is lazy loaded on some objects it throws a LazyInitializationException stating there is no session or the session is closed. After taking out the code into a clean console app for testing - I'm convinced the session simply cannot be closed! Here is the code:
private static ISessionFactory _sessionFactory;
static void Main(string[] args)
{
_sessionFactory = BuildFactory(@"*<ThisIsMyConnectionString>*");
using (var session = _sessionFactory.OpenSession())
{
var allContacts = session.Query<Contact>().Where(x=>x.EmployeeId.HasValue);
foreach (var contact in allContacts)
{
var allServices = contact.EmployeeServices.ToArray();
}
session.Dispose();
}
}
private static ISessionFactory BuildFactory(string connectionString = null)
{
return Fluently.Configure()
.Database(FluentNHibernate.Cfg.Db.MsSqlConfiguration.MsSql2008.ConnectionString(connectionString))
.Mappings(m =>
{
m.FluentMappings.Conventions.AddFromAssemblyOf<TableNameConvention>();
m.FluentMappings.AddFromAssemblyOf<KioskAdapterConfigMapping>();
})
.BuildConfiguration().BuildSessionFactory();
}
And here is my (fluent) mappings:
public ServiceMapping()
{
Table("tblServices");
Id(x => x.Id, "ServiceId");
Map(x => x.Name);
}
public ContactMapping()
{
Table("tblContacts");
Id(x => x.Id, "ContactId");
Map(x => x.EmployeeId);
HasManyToMany(x => x.EmployeeServices)
.Table("lnkEmployeeService")
.ParentKeyColumn("EmployeeId")
.PropertyRef("EmployeeId")
.ChildKeyColumn("ServiceId")
.NotFound.Ignore();
}
How on earth is the session closed? Some database records do not have any records in the "lnkEmployeeService" table, but all foreign keys are in place and valid. Also the link table does have extra columns and is actually a composite key with other columns, but I don't care about rest of the data.