DbMigrationCommand.cs 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using Microsoft.EntityFrameworkCore;
  7. using Microsoft.EntityFrameworkCore.Infrastructure;
  8. using Microsoft.EntityFrameworkCore.Migrations;
  9. using Microsoft.Extensions.DependencyInjection;
  10. using Quadarax.Application.QLiberace.Base;
  11. using Quadarax.Foundation.Core.QConsole;
  12. namespace Quadarax.Application.QLiberace.Console.Commands.Base
  13. {
  14. internal abstract class DbMigrationCommand : DbContextCommand
  15. {
  16. #region *** Properties ***
  17. #endregion
  18. #region *** Constructor ***
  19. protected DbMigrationCommand(Engine engine) : base(engine)
  20. {
  21. }
  22. #endregion
  23. #region *** EXECUTE ***
  24. #endregion
  25. #region *** Private operations ***
  26. //src: https://makolyte.com/ef-core-apply-migrations-programmatically/
  27. protected void ApplyMigration(DbContext context, string? migrationCode = null)
  28. {
  29. var migrator = context.GetInfrastructure().GetService<IMigrator>();
  30. if (migrator == null)
  31. throw new InvalidOperationException($"Cannot obtain service IMigrator from EFC6 infrastructure.");
  32. migrator.Migrate(migrationCode);
  33. var lastAppliedMigration = (context.Database.GetAppliedMigrations()).Last();
  34. WriteInfo($"You're now on schema version: {lastAppliedMigration}");
  35. }
  36. protected bool CheckPendingMigrations(DbContext context)
  37. {
  38. return context.Database.GetPendingMigrations().Any();
  39. }
  40. #endregion
  41. }
  42. }