2013-02-15 76 views
2

我正在用NUnit和Entity Framework編寫一些UnitTests。 如何從實體框架級別刪除整個localdb數據庫?在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的引用

回答

5

有兩種方法可以在代碼中執行此操作。如果可以,請先堅持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; 
    } 
+0

謝謝,非常有用的答案。在閱讀之前,我通過生成一個新的Guid在TestFixture中創建了一個新的數據庫,以便每次都重新創建數據庫(及其結構)。然後我從SQL Management Studio級別刪除所有數據庫。 – lixonn 2013-02-21 11:30:16

相關問題