2

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..

ファイル「UnitTestDB.mdf」だけを削除するだけでは不十分です。SQL Management Studio にはまだ db への参照があります

4

2 に答える 2

5

コードでこれを行うには2つの方法があります。可能であれば、最初にEFコードに固執してください:-)

1)EFには、コンテキストに関する優れたオプションがあります。

 Context.Database.Delete()

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;
    }
于 2013-02-15T13:49:22.693 に答える