lix*_*onn 2 entity-framework code-first ef-code-first localdb
我正在用NUnit和Entity Framework编写一些UnitTests.如何从Entity Framework级别删除整个localdb数据库?
注意:我不想清除表的数据.我想删除整个数据库.
此外,我可以在我的应用程序工作目录中创建一个localdb文件,前提是尚未创建数据库:
string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "");
var testDbFileName = String.Format(@"UnitTestDB.mdf");
var testDbFileNameWithPath = path + @"\" + testDbFileName;
var connectionString =
String.Format(
@"Data Source=(localdb)\V11.0;Initial Catalog={0};Integrated Security=True;AttachDBFilename={1};MultipleActiveResultSets=True",
"UnitTestDB", testDbFileNameWithPath);
//Here would be the code passing connection string to DbContext and so on..
Run Code Online (Sandbox Code Playgroud)
仅删除文件"UnitTestDB.mdf"是不够的.在SQL Management Studio中仍然有对db的引用
在代码中有两种方法可以做到这一点.如果可以,请先坚持使用EF代码:-)
1)EF在上下文中有一个很好的选择.
Context.Database.Delete()
Run Code Online (Sandbox Code Playgroud)
2)如果你想要旧学校的SQLCommand/SqlConnection方法就像这样的黑客例程...
public bool DropDB(string DBName, string ConnectionString)
{
SqlConnection conn = null;
SqlCommand cmd = null;
string stmt = null;
int rowCount = 0;
if (string.IsNullOrEmpty(DBName))
throw new ArgumentNullException(DBName, "DBName required");
try
{
conn = new SqlConnection(ConnectionString);
stmt = "DROP DATABASE " + DBName ;
cmd = new SqlCommand(stmt, conn);
conn.Open();
rowCount = cmd.ExecuteNonQuery();
conn.Close();
}
catch (Exception)
{
//todo whatever
throw;
}
finally
{
if (conn != null) conn.Dispose();
if (cmd != null) conn.Dispose();
}
if (rowCount == -1) return true;
return false;
}
Run Code Online (Sandbox Code Playgroud)