Windows 应用程序的 Nhibernate 会话配置



我在 Windows 窗体应用程序中使用 NHibernate,我需要更改存储库类中的连接字符串。但是当我尝试获取当前会话时,出现此错误:

No CurrentSessionContext configured

我的存储库类如下:

public class UserRepository : Repository<User>, IUserRepository
    {
        public UserRepository(ISessionFactory planningUow) : base(planningUow)
        {
            planningUow.GetCurrentSession().Connection.ConnectionString = "test";
        }
        public IQueryable<User> GetByUserId(Guid id)
        {
            return Session.Query<User>().Where(bd => bd.UserId == id).AsQueryable();
        }
        public IQueryable<User> GetAllUsers()
        {
            return Session.Query<User>().AsQueryable();
        }
        public IQueryable<User> GetByUserPassword(string userName, string password)
        {
            return Session.Query<User>().Where(x => x.UserName == userName && x.Password == password).AsQueryable();
        }
    }

我的 Fluent Nhibernate 配置代码如下:

public ISessionFactory CreateSessionFactory()
        {
            try
            {
                return Fluently.Configure()
                .Database(MsSqlConfiguration.MsSql2008.ConnectionString(x => x.FromConnectionStringWithKey(ConnectionString)))
               .Mappings(m =>
                         m.FluentMappings
                             .AddFromAssemblyOf<UserMap>())               
                .ExposeConfiguration(config => { new SchemaUpdate(config).Execute(false, true); })
                .BuildSessionFactory();
            }
            catch (Exception ex)
            {
                throw ex;
            }       
        }

如何获取当前会话以获取连接字符串?

我认为一旦

构建了SessionFactory,您将无法更改连接设置。但是,您可以提供自己的Session连接。如何使用上下文会话来做到这一点尚不清楚,因为您尚未包含该代码。

根据您计划使用的不同连接的数量,多SessionFactory方法可能是最好的。

最新更新