Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.
 
 
 

78 рядки
2.3 KiB

  1. using System.Data;
  2. using System.Data.SqlClient;
  3. using System.Threading;
  4. using Dapper;
  5. namespace DotNetCore.CAP.SqlServer.Test
  6. {
  7. public abstract class DatabaseTestHost : TestHost
  8. {
  9. private static bool _sqlObjectInstalled;
  10. public static object _lock = new object();
  11. protected override void PostBuildServices()
  12. {
  13. base.PostBuildServices();
  14. lock (_lock)
  15. {
  16. if (!_sqlObjectInstalled)
  17. {
  18. InitializeDatabase();
  19. }
  20. }
  21. }
  22. public override void Dispose()
  23. {
  24. DeleteAllData();
  25. base.Dispose();
  26. }
  27. private void InitializeDatabase()
  28. {
  29. using (CreateScope())
  30. {
  31. var storage = GetService<SqlServerStorage>();
  32. var token = new CancellationTokenSource().Token;
  33. CreateDatabase();
  34. storage.InitializeAsync(token).GetAwaiter().GetResult();
  35. _sqlObjectInstalled = true;
  36. }
  37. }
  38. private void CreateDatabase()
  39. {
  40. var masterConn = ConnectionUtil.GetMasterConnectionString();
  41. var databaseName = ConnectionUtil.GetDatabaseName();
  42. using (var connection = ConnectionUtil.CreateConnection(masterConn))
  43. {
  44. connection.Execute($@"
  45. IF NOT EXISTS (SELECT * FROM sysdatabases WHERE name = N'{databaseName}')
  46. CREATE DATABASE [{databaseName}];");
  47. }
  48. }
  49. private void DeleteAllData()
  50. {
  51. var conn = ConnectionUtil.GetConnectionString();
  52. using (var connection = new SqlConnection(conn))
  53. {
  54. var commands = new[] {
  55. "DISABLE TRIGGER ALL ON ?",
  56. "ALTER TABLE ? NOCHECK CONSTRAINT ALL",
  57. "DELETE FROM ?",
  58. "ALTER TABLE ? CHECK CONSTRAINT ALL",
  59. "ENABLE TRIGGER ALL ON ?"
  60. };
  61. foreach (var command in commands)
  62. {
  63. connection.Execute(
  64. "sp_MSforeachtable",
  65. new { command1 = command },
  66. commandType: CommandType.StoredProcedure);
  67. }
  68. }
  69. }
  70. }
  71. }