我无法弄清楚为什么我在课堂上调用第二个查询时关闭了会话。
首先我调用方法 getPoliceData() 我运行良好之后我调用 GetSkadeData() 并抛出错误:
DbFactory 类看起来像这样
class DbFactory
{
private static Lazy<ISessionFactory> factory = new Lazy<ISessionFactory>(GetSessionFactory, System.Threading.LazyThreadSafetyMode.ExecutionAndPublication);
public DbFactory()
{
}
public List<PoliceData> getPoliceData() {
using (ISession session = OpenSession())
{
IList<PoliceData> pols = session.Query<PoliceData>().Where(p => p.policyNumber == 053126703).ToList();
return pols.ToList();
}
}
public List<SkadeData> getSkadeData()
{
using (ISession session = OpenSession())
{
IList<SkadeData> skader = session.Query<SkadeData>().Where(p => p.Postnr == "7700").ToList();
return skader.ToList();
}
}
private static ISession OpenSession()
{
return factory.Value.GetCurrentSession();
}
private static ISessionFactory GetSessionFactory()
{
//NHibernate.Cfg.Configuration
var c = new Configuration();
//c.Configure();
c.DataBaseIntegration(db =>
{
db.ConnectionString = "Server=\"localhost\";database=testdb;Integrated Security=SSPI";
db.Dialect<NHibernate.Dialect.MsSql2012Dialect>();
});
//c.Configure("c:\XML.xml");
ModelMapper maps = new ModelMapper();
maps.AddMapping<PoliceDataMap>();
maps.AddMapping<SkadeDataMap>();
c.AddMapping(maps.CompileMappingForAllExplicitlyAddedEntities());
c.CurrentSessionContext<NHibernate.Context.ThreadLocalSessionContext>();
//c.Configure().Configure();
var sessionFac = c.BuildSessionFactory();
return sessionFac;
//return sessionFac.GetCurrentSession();
}
}
当我从另一个类调用该方法时,我正在这样做
List<PoliceData> test = new List<PoliceData>();
List<SkadeData> skader = new List<SkadeData>();
DbFactory poli = new DbFactory();
test = poli.getPoliceData();
skader = poli.getSkadeData();
我是否需要创建一个新的 dbfactory 实例,或者是否可以将同一个会话用于两个不同的查询。如果 Nhibernate 只配置一次,然后您只需在需要时打开和关闭会话,那就太好了。