【问题标题】:Use settings.json on a Net Core Class Library with EF Core migrations在具有 EF Core 迁移的 Net Core 类库上使用 settings.json
【发布时间】:2019-04-11 23:18:59
【问题描述】:

在 NET Core 2.1 类库中,我有一个 Entity Framework Core 2.1 DbContext:

public class AppContext : IdentityDbContext<User, Role, Int32> {

  public AppContext(DbContextOptions options) : base(options) { }

}

要在类库上运行迁移,我需要添加以下内容:

public class ContextFactory : IDesignTimeDbContextFactory<Context> {

  public Context CreateDbContext(String[] args) {

    DbContextOptionsBuilder builder = new DbContextOptionsBuilder<Context>();

    builder.UseSqlServer(@"Server=localhost;Database=db;User=sa;Password=pass;");

    return new Context(builder.Options);

  } 

}

有了这个,我可以在类库命令上运行,例如:

dotnet ef migrations add "InitialCommit"
dotnet ef database update

但是如何将连接字符串移动到类库中的 settings.json 文件中呢?

【问题讨论】:

    标签: asp.net-core entity-framework-core dotnet-cli


    【解决方案1】:

    IDesignTimeDbContextFactory,顾名思义,是专门用于开发的。通常不需要外部化连接字符串,因为它应该是相当静态的,即使在团队环境中也是如此。也就是说,如果有的话,您应该将其存储在用户机密中,因为这仅用于开发。使用用户机密可将连接字符串排除在源代码管理之外,因此您团队中的开发人员不会互相干扰对方的连接字符串。

    var config = new ConfigurationBuilder()
        .AddUserSecrets()
        .Build();
    
    var connectionString = config.GetConnectionString("Foo");
    

    【讨论】:

      【解决方案2】:

      IDesignTimeDbContextFactory&lt;&gt; 实现通过 EF 实用程序进程运行。这是一个常规控制台应用程序,您可以在其中使用Console.Write()Console.Read() 与执行迁移和更新的用户进行交互。这允许您在更新时提示用户输入他们的连接字符串。

      public class Builder : IDesignTimeDbContextFactory<AppContext>
      {
          public AppContext CreateDbContext(string[] args)
          {
              Console.Write("Enter your connection string: ");
              var conStr = Console.ReadLine();
      
              var options = new DbContextOptionsBuilder<AppContext>().UseSqlServer(conStr).Options;
      
              return new AppContext(options);
          }
      }
      

      【讨论】:

        【解决方案3】:

        您可以在启动类中配置 DbContextOptions,然后将其注入上下文。在 Startup 类中,您可以从 Configuration 获取连接字符串。

        Startup.cs:

          public void ConfigureServices(IServiceCollection services)
                {                        
                services.AddDbContext<Context>
                (options=> options.UseSqlServer(Configuration["ConnectionString:DefaultConnection"]));
        
                ....
                }
        

        将连接字符串添加到 appsettings.json:

          "ConnectionString": {
            "DefaultConnection": "your connection string"
          },
        

        【讨论】:

        • 正确,但是要使用 EF 迁移,包含上下文的库需要实现 IDesignTimeDbContextFactory&lt;&gt;,它返回一个实例化的上下文(因此需要库内的连接字符串用于设计时。)
        猜你喜欢
        • 2019-10-08
        • 2021-12-29
        • 1970-01-01
        • 1970-01-01
        • 2021-11-23
        • 2021-10-17
        • 2019-07-06
        • 1970-01-01
        • 2022-07-15
        相关资源
        最近更新 更多