问题描述
有了这个简单的代码,我得到无法删除数据库test_db因为它正在使用(CleanUp方法),因为我运行它。
Having this simple code I get "Cannot drop database "test_db" because it is currently in use" (CleanUp method) as I run it.
[TestFixture]
public class ClientRepositoryTest
{
private const string CONNECTION_STRING = "Data Source=.;Initial Catalog=test_db;Trusted_Connection=True";
private DataContext _dataCntx;
[SetUp]
public void Init()
{
Database.SetInitializer(new DropCreateDatabaseAlways<DataContext>());
_dataCntx = new DataContext(CONNECTION_STRING);
_dataCntx.Database.Initialize(true);
}
[TearDown]
public void CleanUp()
{
_dataCntx.Dispose();
Database.Delete(CONNECTION_STRING);
}
}
DataContext有一个这样的属性
DataContext has one property like this
public DbSet<Client> Clients { get; set; }
如何强制我的代码删除数据库?
谢谢
How can force my code to remove database?Thanks
推荐答案
问题是您的应用程序可能仍然保持与数据库的一些连接(或另一个应用程序保持连接)。数据库不能被删除的地方有任何其他打开的连接。第一个问题可能是通过关闭连接池来解决(将 Pooling = false
添加到连接字符串),或者在删除数据库之前清除该池(通过调用 SqlConnection.ClearAllPools()
)。
The problem is that your application probably still holds some connection to the database (or another application holds connection as well). Database cannot be deleted where there is any other opened connection. The first problem can be probably solved by turning connection pooling off (add Pooling=false
to your connection string) or clear the pool before you delete the database (by calling SqlConnection.ClearAllPools()
).
这两个问题都可以通过强制数据库删除来解决,但是您需要自定义数据库初始化程序将数据库切换到单用户模式,然后将其删除。 是一些例子如何实现。
Both problems can be solved by forcing database to delete but for that you need custom database initializer where you switch the database to single user mode and after that delete it. Here is some example how to achieve that.
这篇关于“无法删除数据库,因为它当前正在使用”。怎么修?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!