简体   繁体   中英

Create Dbcontext at run-time

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM