我遇到了一个真正令人沮丧的问题,并花了几个小时尝试各种方法来解决。当集合在某些对象上延迟加载时,它会抛出 LazyInitializationException 说明没有会话或会话已关闭。将代码取出到干净的控制台应用程序中进行测试后 - 我确信会话根本无法关闭!这是代码:
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();
}
这是我的(流利的)映射:
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();
}
会话到底是如何关闭的?一些数据库记录在“lnkEmployeeService”表中没有任何记录,但所有外键都到位且有效。此外,链接表确实有额外的列,实际上是与其他列的复合键,但我不关心其余数据。