You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

63 lines
1.2 KiB

  1. using System.Data;
  2. using System.Threading.Tasks;
  3. using Dapper;
  4. using Microsoft.EntityFrameworkCore;
  5. namespace DotNetCore.CAP.EntityFrameworkCore.Test
  6. {
  7. public abstract class DatabaseTestHost : TestHost
  8. {
  9. private static bool _sqlObjectInstalled;
  10. protected override void PostBuildServices()
  11. {
  12. base.PostBuildServices();
  13. InitializeDatabase();
  14. }
  15. public override void Dispose()
  16. {
  17. DeleteAllData();
  18. base.Dispose();
  19. }
  20. private void InitializeDatabase()
  21. {
  22. if (!_sqlObjectInstalled)
  23. {
  24. using (CreateScope())
  25. {
  26. var context = GetService<TestDbContext>();
  27. context.Database.EnsureDeleted();
  28. context.Database.Migrate();
  29. _sqlObjectInstalled = true;
  30. }
  31. }
  32. }
  33. private void DeleteAllData()
  34. {
  35. using (CreateScope())
  36. {
  37. var context = GetService<TestDbContext>();
  38. var commands = new[]
  39. {
  40. "DISABLE TRIGGER ALL ON ?",
  41. "ALTER TABLE ? NOCHECK CONSTRAINT ALL",
  42. "DELETE FROM ?",
  43. "ALTER TABLE ? CHECK CONSTRAINT ALL",
  44. "ENABLE TRIGGER ALL ON ?"
  45. };
  46. foreach (var command in commands)
  47. {
  48. context.Database.GetDbConnection().Execute(
  49. "sp_MSforeachtable",
  50. new { command1 = command },
  51. commandType: CommandType.StoredProcedure);
  52. }
  53. }
  54. }
  55. }
  56. }