【问题标题】:How to pass ConnectionString from appsettings.json file to class library project in dot net core 2.2如何将连接字符串从 appsettings.json 文件传递​​到 dot net core 2.2 中的类库项目
【发布时间】:2019-05-22 03:40:57
【问题描述】:

我的解决方案中有两个项目。一个是 Angular Core 2.2 Web 应用程序,另一个是包含域模型和 dbcontext 的类库项目。 我想将连接字符串传递给 dbcontext,以便我可以使用代码优先方法创建数据库。 这是我的连接字符串

"ConnectionStrings": {
"DataConnection": "Server=.;Database=Test;Trusted_Connection=True;MultipleActiveResultSets=true;Integrated Security=True;"

这是 ConfigureService 方法中的代码

 public void ConfigureServices(IServiceCollection services)
    {
        services.AddDbContextPool<TestContext>(context => context.UseSqlServer(Configuration.GetConnectionString("DataConnection")));
        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
    }

}

这是我的 DBContext

public class TestContext : DbContext
{
 public CCPGV1Context(string connectionString):base(connectionString)
    {

    }

protected override void OnModelCreating(ModelBuilder modelBuilder)
    {

        base.OnModelCreating(modelBuilder);
    }
}

我不熟悉代码优先方法以及 dot net core。请指导我该怎么做!

【问题讨论】:

    标签: c# .net ef-code-first ef-core-2.0 .net-core-2.2


    【解决方案1】:

    由于您将连接字符串配置为服务,因此您可以像这样简单地注入 DbContext 类的构造函数:

    public class TestContext : DbContext 
      { 
      public TestContext(DbContextOptions<TestContext> options):base(options)
             {
    
             }
       }
    

    【讨论】:

      【解决方案2】:

      您必须将IConfiguration 接口作为参数从Microsoft.Extensions.Configuration 传递给Startup 类的构造函数(随便命名,例如出于目的,我将其命名为_configuration)。

      然后,替换这一行

      services.AddDbContextPool<TestContext>(context => context.UseSqlServer(Configuration.GetConnectionString("DataConnection")));
      

      用这个:

      services.AddDbContext<TestContext>(options => options.UseSqlServer(_configuration.GetConnectionString("DataConnection")));
      

      在 thar 之后,将这个构造函数添加到你 TestContext 类:

      public TestContext(DbContextOptions<TestContext> options) : base(options)
              {
      
              }
      

      这用于播种DBContextOptions 类,并在Startup.cs 中为TestContext 建立配置

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-11-18
        • 1970-01-01
        • 1970-01-01
        • 2020-01-22
        • 1970-01-01
        • 2018-12-20
        相关资源
        最近更新 更多