Page 1 of 1

How change connection string runtime in ef core?

Posted: Fri 18 Aug 2017 05:58
by keng
Hi
How change connection string runtime in ef core?
I try to change connection string on runtime but data no change.

Code: Select all

public string ConnectionString { get; set; }
        public EFDbContext() :
            base()
        {
            OnCreated();
        }

        public EFDbContext(DbContextOptions<EFDbContext> options) :
            base(options)
        {
            OnCreated();
        }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder.UseMySql(ConnectionString);
            CustomizeConfiguration(ref optionsBuilder);
            base.OnConfiguring(optionsBuilder);
        }

Please help me.

Re: How change connection string runtime in ef core?

Posted: Fri 18 Aug 2017 09:16
by Shalex
You can set connection string used by EF Core context in runtime:

Code: Select all

        var optionsBuilder = new DbContextOptionsBuilder<ModelContext>();
        optionsBuilder.UseMySql(@"User Id=root;Password=root;Host=db;Port=3311;Database=aaaa;");
        var context = new ModelContext(optionsBuilder.Options);
        var result = context.Depts.ToList();

        var optionsBuilder2 = new DbContextOptionsBuilder<ModelContext>();
        optionsBuilder2.UseMySql(@"User Id=root;Password=root;Host=db;Port=3312;Database=bbbb;");
        var context2 = new ModelContext(optionsBuilder2.Options);
        var result2 = context2.Depts.ToList();
There is a known issue: our EF Core template currently generates the following code

Code: Select all

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder.UseMySql(@"...");
            CustomizeConfiguration(ref optionsBuilder);
            base.OnConfiguring(optionsBuilder);
        }
which overrides connection string set via your own code. We will fix code generation in this way

Code: Select all

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            if (!optionsBuilder.Options.Extensions.OfType<RelationalOptionsExtension>().Any(ext => !string.IsNullOrEmpty(ext.ConnectionString) || ext.Connection != null))
                optionsBuilder.UseMySql(@"...");

            CustomizeConfiguration(ref optionsBuilder);
            base.OnConfiguring(optionsBuilder);
        }
and will notify you when the change is included in a predefined EF Core template.

Re: How change connection string runtime in ef core?

Posted: Fri 08 Sep 2017 13:13
by Shalex
The issue is fixed in the new (8.9.980) build of dotConnect for MySQL.