我在我的EF codefirst Seed方法中尝试以下内容:
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);
}
}
}
我知道如何通过代码实现这一点(我正在尝试自动化测试)?
答案 0 :(得分:1)
在服务器资源管理器中,右键单击与该数据库的数据连接,然后选择关闭连接。