使用 Key Vault 和包管理器控制台为 Entity Framework Core 连接和数据库迁移

Posted

技术标签:

【中文标题】使用 Key Vault 和包管理器控制台为 Entity Framework Core 连接和数据库迁移【英文标题】:Connecting and Databse Migration for Entity Framework Core using Key Vault and Package Manager Console 【发布时间】:2020-02-26 11:23:28 【问题描述】:

我将 appSettings.config 更改为不再有连接字符串,因为它们现在都在 Azure Key Vault 中。我能够连接没有问题,但是现在当我尝试使用 EF 代码创建数据库时,首先使用

在新的 azure db 中迁移

添加迁移初始创建

Value cannot be null.
Parameter name: connectionString

我收到错误:

        public Startup(IHostingEnvironment env)
    
        AutomapperConfiguration.Configure();
        _hostingEnvironment = env;
        var builder = new ConfigurationBuilder()
            .SetBasePath(env.ContentRootPath)
            .AddJsonFile("appsettings.json", false, true)
            .AddJsonFile($"appsettings.env.EnvironmentName.json", true)
            .AddEnvironmentVariables();

        if (env.EnvironmentName == Constant.EnvironmentName_QA || env.EnvironmentName == Constant.EnvironmentName_Staging || env.EnvironmentName == Constant.EnvironmentName_Production)
            env.ConfigureNLog($"nlog.env.EnvironmentName.config");
        else
            env.ConfigureNLog($"nlog.config");


        builder.AddAzureKeyVault(Configuration["AzureVault:Vault"], Configuration["AzureVault:ClientId"], Configuration["AzureVault:ClientSecret"]);

        Configuration = builder.Build();

      




Configuration()
.
.
.
services.AddDbContext<SafeContext>(options => options.UseSqlServer(Configuration[Configuration["AzureVaultKeys:DBConnectionString"]]));
.
.
.

【问题讨论】:

您还有其他顾虑吗?如果您没有其他顾虑,可以请accept the answer吗? 【参考方案1】:

根据我的测试,我们可以使用以下步骤来实现迁移

    安装 SDK
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="3.1.2" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="3.1.2" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="3.1.2">
      <PrivateAssets>all</PrivateAssets>
      <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
    </PackageReference>
<PackageReference Include="Microsoft.Extensions.Configuration.AzureKeyVault" Version="3.1.2" />

    代码

    一个。程序.cs

     public static void Main(string[] args)
       
    
           var host = CreateHostBuilder(args).Build();
    
           using (var scope = host.Services.CreateScope())
           
               var services = scope.ServiceProvider;
               try
               
                   var context = services.GetRequiredService<SchoolContext>();
                   DbInitializer.Initialize(context);
               
               catch (Exception ex)
               
                   var logger = services.GetRequiredService<ILogger<Program>>();
                   logger.LogError(ex, "An error occurred while seeding the database.");
               
           
    
           host.Run();
       
    
       public static IHostBuilder CreateHostBuilder(string[] args) =>
           Host.CreateDefaultBuilder(args)
       .ConfigureAppConfiguration((context, config) =>
       
    
           config.SetBasePath(context.HostingEnvironment.ContentRootPath)
                  .AddJsonFile("appsettings.json", false, true)
                  .AddJsonFile($"appsettings.context.HostingEnvironment.EnvironmentName.json", true)
                  .AddEnvironmentVariables();
           var builtConfig = config.Build();
           config.AddAzureKeyVault(
                       $"https://builtConfig["KeyVault:Vault"].vault.azure.net/",
                       builtConfig["KeyVault:ClientId"],
                       builtConfig["KeyVault:ClientSecret"],
                       new DefaultKeyVaultSecretManager());
    
    
       )
       .ConfigureWebHostDefaults(webBuilder =>
       
           webBuilder.UseStartup<Startup>();
       );
    

    b.启动.cs

    public void ConfigureServices(IServiceCollection services)
        
            services.AddDbContext<SchoolContext>(options =>
        options.UseSqlServer(Configuration["<your secret name>"])); //For example you secret name is ConnectionStrings--DefaultConnection, the code is  Configuration["ConnectionStrings:DefaultConnection"]  
            services.AddControllersWithViews();
        
    

3 迁移

add-migration InitialCreate

更多详情请参考

https://docs.microsoft.com/en-us/aspnet/core/security/key-vault-configuration?view=aspnetcore-3.1

https://docs.microsoft.com/en-us/aspnet/core/data/ef-mvc/intro?view=aspnetcore-3.1

【讨论】:

以上是关于使用 Key Vault 和包管理器控制台为 Entity Framework Core 连接和数据库迁移的主要内容,如果未能解决你的问题,请参考以下文章

Azure RM 模板。使用 Key Vault 密码部署副本 VM

Angular - Azure Key Vault 管理 Vault 访问机密

Azure Key Vault 机密查询

vault key 管理工具

使用vault管理Kubernetes Secret

net core 应用程序无法访问 azure key Vault