[英]Create Dbcontext at run-time
我需要在运行时切换到不同的数据源。 有时用户想要连接到不同的数据库服务器来操作数据。 可以有超过 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);
}
}
如果您使用AddDbContext
调用注册您的数据库,您可以利用它的重载,它为您提供对IServiceProvider
的访问:
public void ConfigureServices(IServiceCollection services)
{
services
.AddEntityFrameworkSqlServer()
.AddDbContext<MyContext>((serviceProvider, options) =>
{
var connectionString = serviceProvider.GetService // get your service
// which can determine needed connection string based on your logic
.GetConnectionString();
options.UseSqlServer(connectionString);
});
}
}
Autofac也可以在这里实现类似的功能。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.