| | | 1 | | using Microsoft.EntityFrameworkCore; |
| | | 2 | | using Microsoft.EntityFrameworkCore.Design; |
| | | 3 | | |
| | | 4 | | namespace Chronicis.Api.Data |
| | | 5 | | { |
| | | 6 | | /// <summary> |
| | | 7 | | /// Design-time factory for creating ChronicisDbContext during migrations. |
| | | 8 | | /// This ensures EF Core tools can create the context without running the full application. |
| | | 9 | | /// |
| | | 10 | | /// Connection string resolution (in order of priority): |
| | | 11 | | /// 1. Environment variable: CHRONICIS_CONNECTION_STRING |
| | | 12 | | /// 2. local.settings.json: ConnectionStrings:ChronicisDb |
| | | 13 | | /// 3. Fallback to localhost SQL Server (for local development) |
| | | 14 | | /// </summary> |
| | | 15 | | public class ChronicisDbContextFactory : IDesignTimeDbContextFactory<ChronicisDbContext> |
| | | 16 | | { |
| | | 17 | | public ChronicisDbContext CreateDbContext(string[] args) |
| | | 18 | | { |
| | 0 | 19 | | var optionsBuilder = new DbContextOptionsBuilder<ChronicisDbContext>(); |
| | | 20 | | |
| | | 21 | | // Try to get connection string from environment variable first |
| | 0 | 22 | | var connectionString = Environment.GetEnvironmentVariable("CHRONICIS_CONNECTION_STRING"); |
| | | 23 | | |
| | | 24 | | // If not found, try to load from local.settings.json |
| | 0 | 25 | | if (string.IsNullOrEmpty(connectionString)) |
| | | 26 | | { |
| | 0 | 27 | | var configuration = new ConfigurationBuilder() |
| | 0 | 28 | | .SetBasePath(Directory.GetCurrentDirectory()) |
| | 0 | 29 | | .AddJsonFile("local.settings.json", optional: true, reloadOnChange: false) |
| | 0 | 30 | | .Build(); |
| | | 31 | | |
| | 0 | 32 | | connectionString = configuration.GetConnectionString("ChronicisDb"); |
| | | 33 | | } |
| | | 34 | | |
| | | 35 | | // Fallback for local development (no secrets in source code) |
| | 0 | 36 | | if (string.IsNullOrEmpty(connectionString)) |
| | | 37 | | { |
| | | 38 | | // This fallback assumes local SQL Server with integrated security |
| | | 39 | | // Developers should set up local.settings.json or environment variable |
| | 0 | 40 | | connectionString = "Server=localhost,1433;Database=Chronicis;Integrated Security=True;TrustServerCertifi |
| | 0 | 41 | | Console.WriteLine("WARNING: Using fallback connection string. Set CHRONICIS_CONNECTION_STRING or configu |
| | | 42 | | } |
| | | 43 | | |
| | 0 | 44 | | optionsBuilder.UseSqlServer(connectionString); |
| | | 45 | | |
| | 0 | 46 | | return new ChronicisDbContext(optionsBuilder.Options); |
| | | 47 | | } |
| | | 48 | | } |
| | | 49 | | } |