[英]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.