如何手动创建的LocalDB使用MDF文件?
问题描述:
我设置了一些单元测试与数据库进行测试工作。我想用的LocalDB V11,但首先我需要创建数据库。我究竟是如何做的呢?
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?
简单地连接到(的LocalDB)V11
在SQL Management Studio中我连接到(我认为)是 C中的数据库:\用户\乔治\
。如何指定一个新的?
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?
在code使用说明书ADO.Net,没有实体框架,以便据我所知,我不能依靠它来简单地创建数据库。
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.
答
只需使用CREATE DATABASE语句
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();
}