-1

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:

  1. 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.
  2. How can I execute the query in Create method?

Documentation of nHibernate failed me hard...

rufus1530
  • 765
  • 4
  • 19

1 Answers1

0

Is there a better way to create database programatically?

Yes. Use the built-in SchemaExport type. Documentation here.

David Osborne
  • 6,436
  • 1
  • 21
  • 35
  • If I understand correctly, SchemaExport is used to create database schema on existing database. What I'm trying to achieve is to create a database when it does not exist and then export schema to it. – rufus1530 Mar 12 '19 at 15:48