.netvisual-studio-2012localdb

How to manually create a mdf file for localdb to use?


I'm setting up some unit tests for testing work done with a database. I would like to use localdb v11 but first I need to create the database. How exactly do I do this?

simply connecting to (localdb)v11 in sql management studio connects me to the database that (I assume) is in C:\Users\George\. How do I specify a new one?

The code uses manual ADO.Net, not Entity Framework so as far as I know I cannot rely on it to simply create the database.


Solution

  • Just use CREATE DATABASE statement

    SqlConnection connection = new SqlConnection(@"server=(localdb)\v11.0");
    using (connection)
    {
        connection.Open();
    
        string sql = string.Format(@"
            CREATE DATABASE
                [Test]
            ON PRIMARY (
               NAME=Test_data,
               FILENAME = '{0}\Test_data.mdf'
            )
            LOG ON (
                NAME=Test_log,
                FILENAME = '{0}\Test_log.ldf'
            )",
            @"C:\Users\George"
        );
    
        SqlCommand command = new SqlCommand(sql, connection);
        command.ExecuteNonQuery();
    }