【发布时间】:2013-05-05 21:49:18
【问题描述】:
我正在我的 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);
}
}
}
知道如何通过代码实现此功能(我正在尝试自动化测试)吗?
【问题讨论】:
-
快速而肮脏的方法就是在运行创建/种子脚本之前删除数据库。在 SSMS 中,您可以选择在删除数据库时关闭现有连接。
-
这就是我现在正在做的事情......这是自动化测试的更大努力的一部分,所以如果可以的话,我想将所有内容都转移到代码中。这一定是一种常见的情况……对吧?
-
您当然可以在运行创建/种子脚本之前运行 SQL 脚本来终止活动连接。但就从 C# 代码运行它而言,它并不是特别自动化:(
-
你有一个时间问题,Membership 事情可能在 Db 初始化程序之前触发(过滤器?)。
标签: c# asp.net asp.net-web-api ef-code-first integration-testing