asp.net-core - 通过 Entity Framework Core 将多个数据库连接到 .NET Core API 项目

标签 asp.net-core asp.net-web-api entity-framework-core

今天我正在学习新的 ASP.net 核心 API 3.1,我想将我的旧网站从 MVC4 转移到 Web API。 除了一件事,一切都很好。数据库连接。在我的旧网站中,我为每个客户端(10/15 数据库)创建了一个数据库,连接后我使用主数据库获取客户端数据库。

这是我的旧 DBContext 代码(此处用于本地测试)

public DBContext(string database)
 : base("Data Source=***SQLServer***;Initial Catalog=" + database + ";Integrated Security=True;Connect Timeout=15;Encrypt=False;TrustServerCertificate=False"){}

我从 DAL 中的 AdminDatabase 获取数据库名称字符串并将其传递给 DBContext。

但是现在有了连接服务,我不知道该怎么做。如果我将连接字符串放在 appsettings json 中,我将无法传递数据库名称参数。

我尝试直接在 startup.cs 文件中指定连接字符串,但我在某处看到这样做不安全,appsetting.json 将连接字符串保密...

如果你有想法,请告诉我 friend ;)

最佳答案

For exemple Jhon connect to DB1 because in his company profile the DB is DB1, and for Jack it's DB2. it's more clear ? and also, i want to be able to create DB, set the name in company parameter in the admindatabase and when the user connected, it use the DB set in admindatabase, and not need to modify the appsettings each time

首先,您可以将所有连接字符串存储在 appsetting.json 文件中:

{
  "ConnectionStrings": {
    "DefaultConnection": "...",
    "DB1Connection": " ...",
    "DB2Connection": " ..."
    //...
  } 
}

然后在dbcontext中,注入(inject)HttpContext获取登录用户信息,通过判断登录用户信息,在OnConfiguring中动态获取对应的连接字符串名 DbContext 的方法。

   public class ApplicationDbContext : IdentityDbContext<IdentityUser>
        {
            private readonly HttpContext httpContext;
            public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options, IHttpContextAccessor httpContextAccessor)
                : base(options)
            {
                httpContext = httpContextAccessor.HttpContext;
            }
            protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
            {
                IConfigurationRoot configuration = new ConfigurationBuilder()
                    .SetBasePath(AppDomain.CurrentDomain.BaseDirectory)
                    .AddJsonFile("appsettings.json")
                    .Build();
                var connectionName = "DefaultConnection";// default connection string
                var userName = httpContext.User?.Identity?.Name;
               //If you distinguish according to the company you belong to, 
               //you can also determine to obtain different connection strings by obtaining the company to which the logged-in user belongs
                if(userName == "Jhon")
                {
                    connectionName = "DB1Connection";
                }
               else if (userName == "Jack"){
                    connectionName = "DB2Connection";
                } 
                optionsBuilder.UseSqlServer(configuration.GetConnectionString(connectionName));
          
            } 
        }
    
     

关于asp.net-core - 通过 Entity Framework Core 将多个数据库连接到 .NET Core API 项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63992439/

相关文章:

entity-framework-core - 选择特定的 Entity Framework 7(核心 1)代码迁移

html - 我将样式设置为移动但图像不会移动

c# - 起订量设置返回 null

asp.net-mvc - ASP.NET MVC 5 和 Web API 2 .NET 要求

c# - 如何仅更新 Entity Framework (核心)中的特定字段

entity-framework-core - 锁定表 Entity Framework 核心的最佳方式

c# - Entity Framework 核心 : How to include a null related Entity with its null column properties?

c# - 在 ASP.NET Core 项目上启用 StyleCop.Analyzers

c# - TimeoutException : The Angular CLI process did not start listening for requests within the timeout period of 0 seconds

c# - 错误 500 网络 API