EF7 change connectionstring at runtime

connection-string entity-framework-core runtime

Question

In the previous versions of EF we were able to alter the dbcontext connection string as below :

context.Database.Connection.ConnectionString = "the new connectionstring";

How can we do this with EF7?

Thank you

Accepted Answer

I found the solution : https://github.com/aspnet/EntityFramework/wiki/Configuring-a-DbContext#config-from-external-code

Context Code

public class BloggingContext : DbContext
{
public BloggingContext(DbContextOptions options)
    : base(options)
{ }

public DbSet<Blog> Blogs { get; set; }
}

Application code

var optionsBuilder = new DbContextOptionsBuilder();
optionsBuilder.UseSqlServer(@"Server=.\SQLEXPRESS;Database=Blogging;integrated security=True;");
var context = new BloggingContext(optionsBuilder.Options);

Thank you



Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why