【问题标题】:How to auto connect from multiple connection strings in dot net core 3.1如何从 dot net core 3.1 中的多个连接字符串自动连接
【发布时间】:2020-08-15 10:09:20
【问题描述】:

这是 appsettings.json 文件中的连接字符串。

appsettings.json

"ConnectionStrings": {
    "DefaultConnection": "Server=DESKTOP-11G3852\\SQLEXPRESS;Database=MyDB;Trusted_Connection=True;MultipleActiveResultSets=true",
    "OfficeConnection": "Server=DESKTOP-DTUS54A;Database=MyDB;Trusted_Connection=True;MultipleActiveResultSets=true",
    "LappyConnection": "Server=DESKTOP-J8PN84H;Database=MyDB;Trusted_Connection=True;MultipleActiveResultSets=true"
  }

Startup.cs

 public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<ApplicationDbContext>(options =>
                options.UseSqlServer(
                    Configuration.GetConnectionString("DefaultConnection")));
            .....
        }

这里的问题是,每次我更换我的机器时,我都必须在 Sratup.cs 文件中手动设置连接。 在这里你可以看到我设置了 "DefaultConnection"

我想要解决方案,比如我在 appsetings.json 文件中有多个连接字符串(现在这里我有 3 个连接字符串),它会检查是否使用第一个连接字符串(DefaultConnection)或不是。

如果没有,那么它将开始与第二个连接字符串(OfficeConnection)建立连接。

如果连接建立成功,那么我的网站应该继续使用第二个连接字符串(OfficeConnection)。


额外: 如果可能我的迁移也需要使用成功连接的连接字符串。

【问题讨论】:

  • 如果您连接到默认数据库实例而不是命名的实例,那么您只需一个连接字符串即可实现此目的:“Server=.;Database=MyDB;Trusted_Connection=True;MultipleActiveResultSets=True”

标签: c# sql-server asp.net-mvc-3 .net-core


【解决方案1】:

这不是正确的做法。配置文件的存在正是出于这个原因,即表明它们在哪个环境中运行:在此处查看此答案:ASP.NET Core set hosting environment in build process

因此,正确的解决方案是根据您运行它的环境更改配置文件。

如果你真的想检查连接性,你可以试试这样:What's the best way to test SQL Server connection programmatically?

/// <summary>
/// Test that the server is connected
/// </summary>
/// <param name="connectionString">The connection string</param>
/// <returns>true if the connection is opened</returns>
private static bool IsServerConnected(string connectionString)
{
    using (SqlConnection connection = new SqlConnection(connectionString))
    {
        try
        {
            connection.Open();
            return true;
        }
        catch (SqlException)
        {
            return false;
        }
    }
}

为您的每个连接字符串并相应地选择。

说实话,您不应该在配置期间执行这些操作,因为这会花费一些时间并使您的应用程序看起来没有响应。

【讨论】:

  • 感谢您的解决方案。我用你的想法满足了我的要求。
  • 很高兴我能帮上忙。不要忘记投票/接受有用的答案。
【解决方案2】:

我通过his 解决方案获得了这个概念,然后我满足了我的要求。

这是您想要将代码粘贴到您的文件中的解决方案

//开始

...

//结束

在下面的解决方案中阻止:

using System;
using System.Collections.Generic;
using System.Linq;
using MySystem.Data;
using Microsoft.Extensions.Configuration;
using Microsoft.Data.SqlClient;
using System.Configuration;

namespace MySystem
{
    public class Startup
    {       
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
            //START
            ConnectionStrings = Configuration.GetSection("ConnectionStrings").GetChildren().ToDictionary(x => x.Key, x => x.Value);            
            ConnString = "";
            foreach (var item in ConnectionStrings)
            {
                if (IsServerConnected(item.Value))
                {
                    ConnString = item.Value;
                    break;
                }
            }
            //END
        }

        public IConfiguration Configuration { get; }
        //START
        public string ConnString { get; }
        public static Dictionary<string, string> ConnectionStrings { get; private set; }
        //END

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {

            //services.AddDbContext<ApplicationDbContext>(options =>
            //    options.UseSqlServer(
            //        Configuration.GetConnectionString("DefaultConnection")));

            //START
            services.AddDbContext<ApplicationDbContext>(options =>
                options.UseSqlServer(
                    ConnString));
            //END
            
            .......
            services.AddRazorPages();           
           
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
           ......
        }

        //START
        private static bool IsServerConnected(string connectionString)
        {
            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                try
                {
                    connection.Open();
                    return true;
                }
                catch (SqlException)
                {
                    return false;
                }
                finally
                {
                    connection.Close();
                }
            }
        }
        //END
    }
}

【讨论】:

    【解决方案3】:

    您可以创建多个 appsetting.json 文件,并在午餐设置中指定您将使用哪些文件。在根 appsettings 中放置不会更改的部分。例如 appsettings.office.json 只有在这种情况下才更改连接。但是,如果您想自动更改它,我认为正确的路径是使用在您的每个环境中设置的环境变量。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-02-19
      • 2020-07-30
      • 2016-10-02
      • 1970-01-01
      • 1970-01-01
      • 2021-07-03
      • 2019-01-07
      • 1970-01-01
      相关资源
      最近更新 更多