Non puoi selezionare più di 25 argomenti Gli argomenti devono iniziare con una lettera o un numero, possono includere trattini ('-') e possono essere lunghi fino a 35 caratteri.
 
 
 

79 righe
2.3 KiB

  1. using System.Data;
  2. using System.Threading;
  3. using Dapper;
  4. using Microsoft.EntityFrameworkCore;
  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).Wait();
  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. using (CreateScope())
  52. {
  53. var context = GetService<TestDbContext>();
  54. var commands = new[]
  55. {
  56. "DISABLE TRIGGER ALL ON ?",
  57. "ALTER TABLE ? NOCHECK CONSTRAINT ALL",
  58. "DELETE FROM ?",
  59. "ALTER TABLE ? CHECK CONSTRAINT ALL",
  60. "ENABLE TRIGGER ALL ON ?"
  61. };
  62. foreach (var command in commands)
  63. {
  64. context.Database.GetDbConnection().Execute(
  65. "sp_MSforeachtable",
  66. new { command1 = command },
  67. commandType: CommandType.StoredProcedure);
  68. }
  69. }
  70. }
  71. }
  72. }