如何传递应用程序.json文本作为一个SQL连接字符串在模型类?(具体的例子)

本文关键字:模型 字符串 连接 一个 文本 json 应用程序 何传递 SQL | 更新日期: 2023-09-27 18:02:34

我正在迁移一个ASP。. NET项目转化为ASP。我试图在。NET Core中实现DbContext功能。我试图将不同的SQL Server信息传递给optionsBuilder,我将其作为参数传递给基本构造函数。我有以下上下文模型类:

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;
        }
...

我想通过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;"
    }
  },

我发现了以下问题,但我相信语法已经改变了一点,因为RC2更新,因为我不能使用解决方案,或者我做错了。

为ASP设置SQL连接字符串。. NET 5 web应用程序在Azure

我如何使用语法类似于Configuration["Data:CompanyFormsContext:ConnectionString"]的SQL Server输入?还是有更好的方法?启动文件中具体应该包含哪些内容?我有以下内容:

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();
}
...

如果有要求,我可以将问题简化为具体询问在模型类中使用appsettings.json。我意识到我在这里有额外的信息来澄清具体情况。

如何传递应用程序.json文本作为一个SQL连接字符串在模型类?(具体的例子)

方案1

您正在尝试为QA加载不同的环境吗?如果是这样,您应该在项目属性中使用一个名为

的环境变量:
ASPNETCORE_ENVIRONMENT : Development

ASPNETCORE_ENVIRONMENT : QA

然后修改launchSettings.json:

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

然后可以为每个环境创建一个单独的Startup.cs文件,称为StartupDevelopment.csStartupQA.cs。这将允许基于环境的不同启动配置文件。

解决方案2

您是否尝试根据上下文加载单独的连接字符串(应用程序中的不同上下文加载不同的连接)?如果是这样:

最好的方法是不使用Context来初始化连接。这应该在Startup.csConfigureServices方法中完成。您可以根据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));
}
现在您的上下文将正确地从JSON文件加载连接字符串。