我目前有一个创建会话工厂的 NHibernateHelper 类。我不断收到错误提示“会话已关闭!”。我会以错误的方式解决这个问题吗?当我调用在 Add(User user) 之后调用的 Add(Login login) 时发生错误
public class NHibernateHelper
{
private static ISessionFactory _sessionFactory;
private static ISessionFactory SessionFactory
{
get
{
if (_sessionFactory == null)
{
var configuration = new Configuration();
configuration.Configure();
configuration.AddAssembly("System.Core");
_sessionFactory = configuration.BuildSessionFactory();
}
return _sessionFactory;
}
}
public static ISession OpenSession()
{
return SessionFactory.OpenSession();
}
}
这是我的存储库:
internal class UserRepository : IUserRepository
{
private ISession _db = NHibernateHelper.OpenSession();
public void Add(User user)
{
using (_db)
{
using (ITransaction transaction = _db.BeginTransaction())
{
IEnumerable<UserRole> userRoles = user.UserRoles;
user.UserRoles = null;
_db.Save(user);
foreach (UserRole userRole in userRoles)
{
userRole.UserID = user.UserID;
_db.Save(userRole);
}
transaction.Commit();
}
}
}
public void Add(Login login)
{
using (_db)
{
using (ITransaction transaction = _db.BeginTransaction())
{
_db.Save(login);
transaction.Commit();
}
}
}
}