AppDbContextDesignTimeFactory.cs 1.2 KB

12345678910111213141516171819202122232425262728
  1. using Microsoft.EntityFrameworkCore;
  2. using Microsoft.EntityFrameworkCore.Design;
  3. using Microsoft.EntityFrameworkCore.Diagnostics;
  4. namespace Infrastructure.Persistence;
  5. /// <summary>
  6. /// Design-time DbContext factory used by 'dotnet ef migrations / database update'.
  7. /// Bypasses the full Host startup (Program.cs) so EF tools don't need to construct
  8. /// Redis / JWT / Mail / etc. services. The connection string is taken from the
  9. /// 'ConnectionStrings__DefaultConnection' environment variable (set by Jenkins or
  10. /// the developer's shell) and falls back to a local SQL Express instance.
  11. /// </summary>
  12. public sealed class AppDbContextDesignTimeFactory : IDesignTimeDbContextFactory<AppDbContext>
  13. {
  14. public AppDbContext CreateDbContext(string[] args)
  15. {
  16. var conn = Environment.GetEnvironmentVariable("ConnectionStrings__DefaultConnection")
  17. ?? "Server=.\\SQLEXPRESS;Database=dpot;Trusted_Connection=True;TrustServerCertificate=True;MultipleActiveResultSets=true";
  18. var options = new DbContextOptionsBuilder<AppDbContext>()
  19. .UseSqlServer(conn)
  20. .ConfigureWarnings(w => w.Ignore(RelationalEventId.PendingModelChangesWarning))
  21. .Options;
  22. return new AppDbContext(options);
  23. }
  24. }