我想在我的EF codefirst種方法如下:無法刪除數據庫,因爲它是在使用(與會員)
protected override void Seed(TestDbContext context)
{
SqlConnection.ClearAllPools();
context.Database.Delete();
context.Database.CreateIfNotExists();
if (!WebMatrix.WebData.WebSecurity.Initialized)
{
WebSecurity.InitializeDatabaseConnection("DefaultConnection", "UserProfile", "UserId", "UserName", autoCreateTables: true);
}
}
這失敗,出現錯誤「無法刪除,因爲數據庫正在使用」。看來我跑我的API項目後纔會發生,它初始化自己的連接到成員表:
private class SimpleMembershipInitializer
{
public SimpleMembershipInitializer()
{
Database.SetInitializer<UsersContext>(null);
try
{
using (var context = new UsersContext())
{
if (!context.Database.Exists())
{
// Create the SimpleMembership database without Entity Framework migration schema
((IObjectContextAdapter)context).ObjectContext.CreateDatabase();
}
}
if (!WebMatrix.WebData.WebSecurity.Initialized)
{
WebSecurity.InitializeDatabaseConnection("DefaultConnection", "UserProfile", "UserId",
"UserName", autoCreateTables: true);
}
}
catch (Exception ex)
{
throw new InvalidOperationException("The ASP.NET Simple Membership database could not be initialized. For more information, please see http://go.microsoft.com/fwlink/?LinkId=256588", ex);
}
}
}
任何想法,我怎麼能得到這個從代碼的工作(我試圖讓測試自動化)?
快速而骯髒的方法只是在運行create/seed腳本之前刪除數據庫。在SSMS中,您可以選擇在刪除數據庫時關閉現有連接。 – dougajmcdonald 2013-05-05 21:51:18
這就是我現在正在做的......這是自動化測試的更大努力的一部分,所以如果可以的話,我想將所有東西都移動到代碼中。這必須是一個常見的情況......對嗎? – SB2055 2013-05-05 21:54:19
在運行創建/種子腳本之前,您當然可以運行SQL腳本來終止活動連接。但它並沒有特別的自動化,因爲從C#代碼中運行它的方式很好:( – dougajmcdonald 2013-05-05 21:55:36