在 .NET 6.0 中的 IDesignTimeDbContextFactory 的方法 CreateDbContext 中为 GetConnectionString 获取配置

Get configuration in method CreateDbContext of IDesignTimeDbContextFactory in .NET 6.0 for GetConnectionString

我需要读取 appsettings.json 的值连接字符串以获得此动态。

我有:

    public class StoreContextFactory : IDesignTimeDbContextFactory<StoreContext>
    {
        public StoreContext CreateDbContext(string[] args)
        {
            var optionsBuilder = new DbContextOptionsBuilder<StoreContext>();
            optionsBuilder.UseSqlServer(@"Server=localhost;Database=StoreCleanArchitecture;Trusted_Connection=True;");

            return new StoreContext(optionsBuilder.Options);
        }
    }

我需要:

    public class StoreContextFactory : IDesignTimeDbContextFactory<StoreContext>
    {
        public StoreContext CreateDbContext(string[] args)
        {
            var defaultConnectionString = configuration.GetConnectionString("DefaultConnection");
            var optionsBuilder = new DbContextOptionsBuilder<StoreContext>();
            optionsBuilder.UseSqlServer(defaultConnectionString);

            return new StoreContext(optionsBuilder.Options);
        }
    }

谢谢。

您可以通过 ConfigurationBuilder:

自行构建配置
public class StoreContextFactory : IDesignTimeDbContextFactory<StoreContext>
{
    public StoreContext CreateDbContext(string[] args)
    {
        // add all needed configuration providers
        IConfigurationRoot configuration = new ConfigurationBuilder()
            .AddJsonFile("appsettings.json")
            .Build();

        var defaultConnectionString = configuration.GetConnectionString("DefaultConnection");
        var optionsBuilder = new DbContextOptionsBuilder<StoreContext>();
        optionsBuilder.UseSqlServer(defaultConnectionString);

        return new StoreContext(optionsBuilder.Options);
    }
}