gpt4 book ai didi

asp.net-core - 我如何在 linq2db 中管理多个数据库

转载 作者:行者123 更新时间:2023-12-04 01:49:17 26 4
gpt4 key购买 nike

我想在我的应用程序中管理多个数据库连接。我正在使用 ASP.NET Core 和 linq2db。对于我的第一个数据库连接,我创建了以下配置并且它工作正常。

public class DatabaseXSettings : ILinqToDBSettings
{
public IEnumerable<IDataProviderSettings> DataProviders
{
get { yield break; }
}

public string DefaultConfiguration => "Oracle.Managed";
public string DefaultDataProvider => "Oracle.Managed";

public string ConnectionString { get; set; }

public DatabaseXSettings(string connectionString)
{
ConnectionString = connectionString;
}

public IEnumerable<IConnectionStringSettings> ConnectionStrings
{
get
{
yield return
new ConnectionStringSettings
{
Name = "DatabaseX",
ProviderName = "Oracle.Managed",
ConnectionString = ConnectionString
};
}
}
}

public static class DatabaseXStartup
{
private static bool _started;
public static void Init(string connectionString)
{
if (!_started)
{
DataConnection.DefaultSettings = new DatabaseXSettings(connectionString);
_started = true;
}
}
}

public class DatabaseX : DataConnection
{
public DatabaseX() : base("DatabaseX") { }
}

对于我的第二个数据库

对于我的第二个数据库连接,我创建了一个类似的配置。但这不起作用。

public class DatabaseYSettings : ILinqToDBSettings
{
.......
}

public static class DatabaseYStartup
{
.......
}


public class DatabaseY : DataConnection
{
public DatabaseY() : base("DatabaseY") { }
}

我的 appsettings.json

  {
"Logging": {
"LogLevel": {
"Default": "Warning"
}
},
"AllowedHosts": "*",
"ConnectionStrings": {
"DatabaseX": "Data Source=..........",
"DatabaseY": "Data Source=.........."
}

LinqToDB.LinqToDBException:“配置‘DatabaseY’未定义。”

还有其他方法吗?

最佳答案

编辑:添加示例

您不需要两个 ILinqToDBSettings 实例。您应该将第二个数据库设置移动到第一个设置类,这样 ConnectionStrings 将返回两个连接字符串。

public class DatabaseSettings : ILinqToDBSettings
{
public IEnumerable<IDataProviderSettings> DataProviders
{
get { yield break; }
}

public string DefaultConfiguration => "Oracle.Managed";
public string DefaultDataProvider => "Oracle.Managed";

private readonly IConnectionStringSettings[] _connectionStrings;

public DatabaseSettings(IConnectionStringSettings[] connectionStrings)
{
_connectionStrings = connectionStrings;
}

public IEnumerable<IConnectionStringSettings> ConnectionStrings => _connectionStrings;
}

public static class DatabaseSetup
{
// just call it on application startup
public static void Init()
{
// create connectionStrings collection with both connection strings from appsettings.json

DataConnection.DefaultSettings = new DatabaseSettings(connectionStrings);
}
}

关于asp.net-core - 我如何在 linq2db 中管理多个数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54020724/

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