有时,使用 LocalDB 的测试的清理代码不会运行(可能是在取消测试时)。结果是很多垃圾本地数据库。
运行尝试创建另一个 localDB 的测试时出现这样的错误
System.Data.SqlClient.SqlException: Unable to create/attach any new database because the number of existing databases has reached the maximum number allowed: 32765.
ved System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
ved System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
ved System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
ved System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
ved System.Data.SqlClient.SqlCommand.RunExecuteNonQueryTds(String methodName, Boolean async, Int32 timeout, Boolean asyncWrite)
ved System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean& usedCache, Boolean asyncWrite, Boolean inRetry)
ved System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
ved Dapper.SqlMapper.ExecuteCommand(IDbConnection cnn, CommandDefinition& command, Action`2 paramReader)
ved Dapper.SqlMapper.ExecuteImpl(IDbConnection cnn, CommandDefinition& command)
ved Dapper.SqlMapper.Execute(IDbConnection cnn, String sql, Object param, IDbTransaction transaction, Nullable`1 commandTimeout, Nullable`1 commandType)
每个测试类中的测试清理都是这样的(使用 xunit)
public override void Dispose()
{
base.Dispose();
FreeDb();
GC.SuppressFinalize(this);
}
private void FreeDb()
{
Task.Factory.StartNew(() =>
{
var masterConnectionString =
@"Data Source=(LocalDB)\MSSQLLocalDB;Integrated Security=True; Initial Catalog=master";
using (var dbConnection = new SqlConnection(masterConnectionString))
{
dbConnection.Execute($"ALTER DATABASE [{_databaseName}] SET OFFLINE WITH ROLLBACK IMMEDIATE");
dbConnection.Execute($"exec sp_detach_db '{_databaseName}'");
}
});
}