2

我正在用 NUnit 和实体框架编写一些单元测试。如何从实体框架级别删除整个 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..

仅删除文件“UnitTestDB.mdf”是不够的。SQL Management Studio 中还有对 db 的引用

4

2 回答 2

5

在代码中有两种方法可以做到这一点。如果可以的话,首先坚持使用 EF 代码:-)

1) EF 在上下文中有一个不错的选择。

 Context.Database.Delete()

2)如果你想要老式的 SQLCommand/SqlConnection 方法,比如这个 hack 例程......

 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;
    }
于 2013-02-15T13:49:22.693 回答
0

您也可以使用 shell 命令将其删除。如果需要,您可以添加带有-U Username -P Password参数的凭据。

查看sqlcmd 文档

sqlcmd -e -S "(LocalDb)\MSSQLLocalDB" -d "master" -Q "EXEC msdb.dbo.sp_delete_database_backuphistory @database_name = N'your-database-name'; USE [master]; DROP DATABASE [your-database-name];"
于 2021-05-26T14:00:37.770 回答