EF7在运行时更改连接字符串

时间:2015-11-03 09:05:32

标签: runtime connection-string entity-framework-core

在以前的EF版本中,我们能够改变dbcontext连接字符串,如下所示:

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

我们如何使用EF7做到这一点?

谢谢

1 个答案:

答案 0 :(得分:3)

我找到了解决方案: https://github.com/aspnet/EntityFramework/wiki/Configuring-a-DbContext#config-from-external-code

上下文代码

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

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

申请代码

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

谢谢