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

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

问题描述

有了这个简单的代码,我得到不能删除数据库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天全站免登陆