“无法删除数据库,因为它当前正在使用中".怎么修? [英] "Cannot drop database because it is currently in use". How to fix?

查看:26
本文介绍了“无法删除数据库,因为它当前正在使用中".怎么修?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有了这个简单的代码,我在运行它时得到无法删除数据库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.

这篇关于“无法删除数据库,因为它当前正在使用中".怎么修?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆