I'm trying to build a simple application that will create a database in my MS SQL Server using raw sql query (I'm using nHibernate 5.2.4). Please note that I'm fairly new to C# therefore the code below is for learning purposes only.
I've written a simple MsSqlSessionManager class that implements methods for opening / closing connections.
public class MsSqlSessionManager : IDatabaseSessionManager
{
private ISession _session;
private readonly ISessionFactory _sessionFactory;
public MsSqlSessionManager(Configuration configuration)
{
_sessionFactory = configuration.BuildSessionFactory();
}
public ISession Open()
{
var session = _sessionFactory.OpenSession();
_session = session;
return session;
}
public void Close(ISession session)
{
_session.Close();
}
}
The DatabaseManager uses the MsSqlSessionManager to open session and execute raw queries. Primarly, this class will be responsible for creating a database.
public class DatabaseManager : IDatabaseManager
{
private readonly IDatabaseSessionManager _sessionManager;
public DatabaseManager(IDatabaseSessionManager sessionManager)
{
_sessionManager = sessionManager;
}
public void Create()
{
using (var session = _sessionManager.Open())
{
session.CreateSQLQuery("create database test_db");
}
}
public void TestQuery()
{
using (var session = _sessionManager.Open())
{
var result = session.CreateSQLQuery("select * from lorem.dbo.ipsum")
.AddScalar("name", NHibernateUtil.String).List();
foreach (var item in result)
{
Console.WriteLine(item);
}
}
}
}
Now if I call TestQuery method (uses a db that's already created), I actually get the correct data (so configuration is ok). However, the Create method doesn't seem to work (nor does it return any error). I assume that the query is not executed, but I cannot find any way to do so.
The questions are:
- Is there a better way to create database programatically? My goal is to use .net console app to create it and according to this post there is no built-in way to do that.
- How can I execute the query in Create method?
Documentation of nHibernate failed me hard...