Create Dbcontext at run-time

冷暖自知 提交于 2021-01-29 05:13:24

问题


I have a requirement to switch to a different data sources at runtime. sometimes user wants to connect to a different database server to manipulate data. There can be more than 100 client servers with an identical database. Original project is a .net core Web API and the server name is an input parameter.

This is what I thought. Is there a better alternative?

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);
        }
    }

回答1:


If you are registering your DB with AddDbContext call you can leverage it's overload which provides you access to 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);
         });
       }
}

Also here something similar is achieved with Autofac.



来源:https://stackoverflow.com/questions/61782214/create-dbcontext-at-run-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!