我正在制作一个使用SQL Server Express/LocalDB的简单桌面应用程序。我在任意非特权位置有一个数据目录,我想在其中创建一个数据库文件。我最初创建了数据库并生成了一个模型供EF使用;现在我想使用该模型在我需要的任何地方重新创建数据库。
我发现了各种帖子做类似的,但他们似乎是删除和重新创建一个现有的数据库通过一个上下文,开始工作,用于测试目的。我想从一个空目录开始。
使用这里代码的摘录,我能够在磁盘上物理地创建数据库文件,使用SQL语句创建新的.mdf和.ldf文件。但他们没有图式;如果我从.mdf文件启动一个上下文实例,然后尝试计数表中的行数,我会得到一个异常,因为表不存在。
如果我尝试调用ctx.Database.Create()
,然后我得到数据库无法创建的错误,因为它已经存在。当然有,只是没有表格。
如果我最初不使用原始SQL查询来创建新的空数据库,并且我尝试如下创建上下文,其中filespec指向有效目录中不存在的.mdf文件,.Create()总是抛出异常" database "无法创建,因为它已经存在"
string connectionString
= "Data Source=(LocalDB)\v11.0;AttachDbFilename="
+ fileSpec;
EventsListDBEntities ctx = new EventsListDBEntities();
ctx.Database.Connection.ConnectionString = connectionString;
ctx.Database.Create();
ctx.Database.Initialize(true);
如何让EF在我的空DB中创建表,或者从头开始创建文件?
试着使用下面的代码:
string connectionString
= "Data Source=(LocalDB)\v11.0;AttachDbFilename="
+ fileSpec;
EventsListDBEntities ctx = new EventsListDBEntities();
ctx.Database.Connection.ConnectionString = connectionString;
ctx.Database.CreateIfNotExists(); // Change this line.
ctx.Database.Initialize(true);
https://msdn.microsoft.com/en-us/library/system.data.entity.database.createifnotexists%28v=vs.113%29.aspx M: System.Data.Entity.Database.CreateIfNotExists
经过多次试验,我最终得到了这样的代码:
string connectionString
= "Data Source=(LocalDB)\v11.0;AttachDbFilename="
+ fileSpec + ";database=EventsListDB";
/* We can't go straight into the context and create the DB because
* it needs a connection to "master" and can't create it. Although this
* looks completely unrelated, under the hood it leaves behind something
* that EF can pick up and use- and it can't hurt to delete any references
* to databases of the same name that may be lurking in other previously
* used directories.
*/
SqlConnectionStringBuilder masterCSB = new SqlConnectionStringBuilder(connectionString);
masterCSB.InitialCatalog = "master";
masterCSB.AttachDBFilename = "";
using (var sqlConn = new SqlConnection(masterCSB.ToString()))
{
sqlConn.Open();
using (var cmd = sqlConn.CreateCommand())
{
bool done = false;
int attempt = 0;
do
{
try
{
cmd.CommandText =
String.Format(
"IF EXISTS (Select name from sys.databases " +
"WHERE name = '{0}') " +
"DROP DATABASE {0}", "EventsListDB");
cmd.ExecuteNonQuery();
done = true;
}
catch (System.Exception ex)
{
/* We sometimes get odd exceptions that're probably because LocalDB hasn't finished starting. */
if (attempt++ > 5)
{
throw ex;
}
else Thread.Sleep(100);
}
} while (!done);
}
}
/* Now we can create the context and use that to create the DB. Note that
* a custom constructor's been added to the context exposing the base
* constructor that can take a connection string- changing the connection
* string after the default constructor reads it from App.config isn't
* sufficient.
*/
EventsListDBEntities ctx = new EventsListDBEntities(connectionString);
ctx.Database.Create();
int numRecords = ctx.EventLists.Count(); //See if it really worked.