I'm using NHibernate in a Windows Forms application and I need to change the connection string in a repository class. But when I try to get the current session I get this error:
No CurrentSessionContext configured
My Repository class is as below:
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();
}
}
and my Fluent Nhibernate configuration code is as below:
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;
}
}
how can I get the current session to get the connection string?
I don't think you'll be able to alter the connection settings once the SessionFactory
is built. However, you can supply your own connection to a Session
. How you will be able to do this with your use of contextual sessions is not clear as you haven't included that code.
Depending on how many different connections you plan to use, a multiple SessionFactory
approach might be best.