【发布时间】:2020-05-13 18:29:58
【问题描述】:
我需要在运行时切换到不同的数据源。有时用户想要连接到不同的数据库服务器来操作数据。可以有超过 100 个具有相同数据库的客户端服务器。原始项目是一个 .net 核心 Web API,服务器名称是一个输入参数。
这就是我的想法。有没有更好的选择?
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
}
public class MyDbContext : DbContext
{
public MyDbContext(DbContextOptions<MyDbContext> options) : base(options)
{
}
public DbSet<Person> Persons { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Person>().HasKey(a => a.Id);
}
}
class Program : IDesignTimeDbContextFactory<MyDbContext>
{
static async Task Main(string[] args)
{
var _context = new Program().CreateDbContext();
//transactions
while (true)
{
var server_name = Console.ReadLine();
if (server_name == "exit")
break;
string[] remoteServer = { server_name };
//new context
using var dbContextRemote = new Program().CreateDbContext(remoteServer);
try
{
dbContextRemote.Database.BeginTransaction();
var result = await dbContextRemote.Persons.FindAsync(1);
//.....
//can be set of queries
Console.WriteLine(result?.Name);
// Commit transaction if all commands succeed, transaction will auto-rollback
dbContextRemote.Database.CommitTransaction();
}
catch (Exception ex)
{
Console.WriteLine(ex);
//dbContextRemote.Database.RollbackTransaction();
break;
}
_context.Database.CloseConnection();
}
}
public MyDbContext CreateDbContext(string[] args = null)
{
if (args == null || args.Length == 0)
args = new string[] { "localhost" };
var optionsBuilder = new DbContextOptionsBuilder<MyDbContext>();
optionsBuilder.UseSqlServer($"Server={args[0]};Database=SampleDb;Trusted_Connection=True");
return new MyDbContext(optionsBuilder.Options);
}
}
【问题讨论】:
-
这种方法有什么问题?我可以轻松地为每个数据库查询创建一个包装器并每次都使用它。
标签: c# entity-framework asp.net-core entity-framework-core ef-core-3.0