这是我的sessionFactory类:
public static ISession OpenSession
{
get
{
try
{
// NHibernateProfiler.Initialize();
if (iSessionFactory == null)
{
lock (syncRoot)
{
if (iSessionFactory == null)
{
Configuration configuration = new Configuration().Configure("hibernate.cfg.xml");
Assembly assembly = Assembly.GetCallingAssembly();
configuration.AddAssembly(assembly);
iSessionFactory = configuration.BuildSessionFactory();
NHibernate.Context.CurrentSessionContext.Bind(iSessionFactory.OpenSession());
return iSessionFactory.OpenSession();
}
}
}
return GetCurrentSession();
}
catch (Exception ex)
{
throw ex;
}
}
}
public static ISession GetCurrentSession()
{
try
{
return iSessionFactory.GetCurrentSession();
}
catch (Exception ex)
{
throw ex;
}
}
这是我的实现类:
private int stock_item_id = 0;
public void testA()
{
//insert a stock item
using (TransactionScope tx = new TransactionScope())
{
using (ISession session = SessionFactory.OpenSession)
{
using (ITransaction transaction = session.BeginTransaction())
{
Stock stock = new Stock()
{
name = "chicken chouwmin"
};
session.Save(stock);
stock_item_id =Convert.ToInt32( stock.id);
var model = session.Get<Stock>(stock_item_id);
}
}
tx.Complete();
}
}
当我将调试器放入
时var model = session.Get(stock_item_id); 我得到一个非空模型
但是当我尝试使用CurrentSession在testB方法中使用相同的代码行删除相同的数据时,我得到null。这是我的第二堂课:
public void testB()
{
//delete a stock item
using (TransactionScope tx = new TransactionScope())
{
using (ISession session = SessionFactory.OpenSession)
{
using (ITransaction transaction = session.BeginTransaction())
{
var model = session.Get<Stock>(stock_item_id);
session.Delete(model);
transaction.Commit();
}
}
tx.Complete();
}
}
通过此方法调用以上两种方法:
public void testC()
{
//call function A and B
using (TransactionScope tx = new TransactionScope())
{
testA();
testB();
tx.Complete();
}
}
背后的原因是什么?如何解决这个问题?