简体   繁体   English

如何将appsettings.json文本作为Model类中的SQL连接字符串传递? (具体例子)

[英]How to pass appsettings.json text as a SQL connection string in Model class? (Specific example)

I am migrating a ASP.NET project into ASP.NET Core and I was trying to implement DbContext functionality in .NET Core. 我正在将ASP.NET项目迁移到ASP.NET Core中,我试图在.NET Core中实现DbContext功能。 I am trying to pass different SQL Server information to the optionsBuilder that I am passing as a parameter to the base constructor. 我试图将不同的SQL Server信息传递给我作为参数传递给基础构造函数的optionsBuilder。 I have the following context model class: 我有以下上下文模型类:

public partial class CompanyFormsContext : DbContext
{
        public CompanyFormsContext() : base (CreateOptions(null))
        {}

        public CompanyFormsContext(string connName) : base (CreateOptions(connName))
        {}

        //NEED TO CONNECT CONFIGURATION HERE
        private static DbContextOptions<CompanyFormsContext> CreateOptions(string connName)
        {
            var optionsBuilder = new DbContextOptionsBuilder<CompanyFormsContext>();

            if (connName == null)
            {
                optionsBuilder.UseSqlServer("Server=(localdb)\\projectsv13;Database=coforms;Trusted_Connection=True;");
            }
            else
            {
                //THIS IS HOW IM TRYING TO MAKE IT
                //similar to --> Configuration["Data:CompanyFormsContext:ConnectionString"]"
                optionsBuilder.UseSqlServer(Configuration["Data:" + connName + ":ConnectionString"]);
            }

            return optionsBuilder.Options;
        }
...

I want to pass in my SQL Server information through the information in appsettings.json which is the following: 我想通过appsettings.json中的信息传递我的SQL Server信息,如下所示:

  "Data": {
    "CompanyFormsContext": {
      "ConnectionString": "Server=(localdb)\\projectsv13;Database=coforms;Trusted_Connection=True;"
    },
    "CompanyFormsContextQA": {
      "ConnectionString": "Server=(localdb)\\projectsv13;Database=coforms;Trusted_Connection=True;"
    }
  },

I have found the following question but I believe the syntax has changed a bit since the RC2 update because I cannot use the solutions or I'm doing it wrong. 我发现了以下问题,但我相信自RC2更新后语法有所改变,因为我无法使用解决方案,或者我做错了。

Setting the SQL connection string for ASP.NET 5 web app in Azure 在Azure中为ASP.NET 5 Web应用程序设置SQL连接字符串

How could I use a syntax similar to Configuration["Data:CompanyFormsContext:ConnectionString"] for the SQL Server input? 如何为SQL Server输入使用类似于Configuration["Data:CompanyFormsContext:ConnectionString"]的语法? Or is there a better way of doing this? 或者有更好的方法吗? What should be in the Startup file specifically? 具体应该在启动文件中应该包含哪些内容? I have the following: 我有以下内容:

public Startup(IHostingEnvironment env)
{
    var builder = new ConfigurationBuilder()
                .SetBasePath(env.ContentRootPath)
                .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
                .AddEnvironmentVariables();
    Configuration = builder.Build();
}

public IConfigurationRoot Configuration { get; set; }

public void ConfigureServices(IServiceCollection services)
{
    // Add framework services.
    services.AddMvc();
    services.AddOptions();
}
...

If requested, I can simplify the question to specifically ask about using appsettings.json in the model class. 如果需要,我可以简化问题,专门询问在模型类中使用appsettings.json I realize that I have extra information here for clarifying the specific situation. 我知道我在这里有额外的信息来澄清具体情况。

Solution 1 解决方案1

Are you trying to load a different environment for QA? 您是否尝试为QA加载不同的环境? If so, you should use an environment variable in your project properties called: 如果是这样,您应该在项目属性中使用一个名为的环境变量:

ASPNETCORE_ENVIRONMENT : Development

or 要么

ASPNETCORE_ENVIRONMENT : QA

Then modify launchSettings.json: 然后修改launchSettings.json:

{
  ...
  "profiles": {
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    },
    "IIS Express (QA)": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "QA"
      }
    }
  }
}

You can then create a separate Startup.cs file for each environment called StartupDevelopment.cs and StartupQA.cs . 然后,您可以为名为StartupDevelopment.csStartupQA.cs每个环境创建单独的Startup.cs文件。 This will allow different start-up profiles based on the environment. 这将允许基于环境的不同启动配置文件。

Solution 2 解决方案2

Are you trying to load separate connection strings based on the context (different contexts in your application load different connections)? 您是否尝试根据上下文加载单独的连接字符串(应用程序中的不同上下文加载不同的连接)? If so: 如果是这样:

The best way to do this is not to use the Context to initialise the connection. 执行此操作的最佳方法是不使用Context初始化连接。 This should be done in the ConfigureServices method in Startup.cs . 这应该在Startup.cs中的ConfigureServices方法中完成。 You can set up your connection strings based on the key in your json files: 您可以根据json文件中的键设置连接字符串:

// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
    // Load the first connection string
    var connectionStringA = Configuration["Data:DefaultConnection:ConnectionStringA"];
    // Load the second connection string
    var connectionStringB = Configuration["Data:DefaultConnection:ConnectionStringB"];
    // Set up Entity Framework
    services.AddEntityFramework()
        .AddSqlServer()
        .AddDbContext<ContextA>(options => options.UseSqlServer(connectionStringA))
        .AddDbContext<ContextB>(options => options.UseSqlServer(connectionStringB));
}

Now your contexts will load the connection strings from the JSON files correctly. 现在,您的上下文将正确加载JSON文件中的连接字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM