gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 04:58:25 31 4
gpt4 key购买 nike

今天我正在学习新的 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 DBis DB1, and for Jack it's DB2. it's more clear ? and also, i want tobe able to create DB, set the name in company parameter in theadmindatabase and when the user connected, it use the DB set inadmindatabase, 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/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com