引言

 

在使用EF时,有时我们需要在程序运行过程中动态更改EF的连接字符串,但不幸的时EF是否对

ConfigurationManager.RefreshSection("xxx")

这行代码的影响不大,我没去深究,还请大侠指点。(本人猜测,EF内部实现没有订阅RefreshSection的事件去做相应的更换连接字符串的处理),如果确实想用该方法通过修改配置文件来实现动态更换连接字符串,那最保守的做法再加上个重启应用程序的方法。(确保EF能重新读到新的配置信息。)

 

这个时候就需要我们在DataContext新建时使用指定DBConnection来解决该问题,Demo如下:

 

APP.CONFIG (Uses EF 6)

<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework">
<parameters>
<parameter value="Data Source=localhost; Integrated Security=True; MultipleActiveResultSets=True" />
</parameters>
</defaultConnectionFactory>
</entityFramework>
</configuration>

the code to make as small as possible for Demo:

using System;
using System.Data.Common;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Data.Entity.Migrations; namespace Ef6Test {
public class Program {
public static void Main(string[] args) {
Database.SetInitializer(new MigrateDatabaseToLatestVersion<Ef6Ctx, Ef6MigConf>());
WhichDb.DbName = "HACKDB1";
var sqlConn = GetSqlConn4DBName(WhichDb.DbName);
var context = new Ef6Ctx(sqlConn);
context.Database.Initialize(true);
AddJunk(context);
//sqlConn.Close(); //?? whatever other considerations, dispose of context etc... Database.SetInitializer(new MigrateDatabaseToLatestVersion<Ef6Ctx, Ef6MigConf>()); // yes its default again reset this !!!!
WhichDb.DbName = "HACKDB2";
var sqlConn2 = GetSqlConn4DBName(WhichDb.DbName);
var context2 = new Ef6Ctx(sqlConn2);
context2.Database.Initialize(true);
AddJunk(context2);
}
public static class WhichDb { // used during migration to know which connection to build
public static string DbName { get; set; }
}
private static void AddJunk(DbContext context) {
var poco = new pocotest();
poco.f1 = DateTime.Now.ToString();
// poco.f2 = "Did somebody step on a duck?"; //comment in for second run
context.Set<pocotest>().Add(poco);
context.SaveChanges();
}
public static DbConnection GetSqlConn4DBName(string dbName) {
var sqlConnFact =
new SqlConnectionFactory(
"Data Source=localhost; Integrated Security=True; MultipleActiveResultSets=True");
var sqlConn = sqlConnFact.CreateConnection(dbName);
return sqlConn;
}
}
public class MigrationsContextFactory : IDbContextFactory<Ef6Ctx> {
public Ef6Ctx Create() {
var sqlConn = Program.GetSqlConn4DBName(Program.WhichDb.DbName); // NASTY but it works
return new Ef6Ctx(sqlConn);
}
}
public class Ef6MigConf : DbMigrationsConfiguration<Ef6Ctx> {
public Ef6MigConf() {
AutomaticMigrationsEnabled = true;
AutomaticMigrationDataLossAllowed = true;
}
}
public class pocotest {
public int Id { get; set; }
public string f1 { get; set; }
// public string f2 { get; set; } // comment in for second run
}
public class Ef6Ctx : DbContext {
public DbSet<pocotest> poco1s { get; set; }
public Ef6Ctx(DbConnection dbConn) : base(dbConn, true) { }
}
}

 

 

参考

https://stackoverflow.com/questions/18272708/how-to-force-dbcontext-refresh-connection-string-from-config

 

https://stackoverflow.com/questions/15504465/entityframework-code-first-custom-connection-string-and-migrations/16133150#16133150

 

https://github.com/mono/entityframework/blob/master/src/EntityFramework/Infrastructure/SqlConnectionFactory.cs

EF6 Create Different DataContext on runtime(运行时改变连接字符串)的更多相关文章

  1. iOS开发——高级特性&Runtime运行时特性详解

    Runtime运行时特性详解 本文详细整理了 Cocoa 的 Runtime 系统的知识,它使得 Objective-C 如虎添翼,具备了灵活的动态特性,使这门古老的语言焕发生机.主要内容如下: 引言 ...

  2. ios - runtime运行时应用---交换方法

    runtime运行时用法之一 --- 交换类的方法,此处简单写了把系统的UIView的setBackgroundColor的方法换成了自定义的pb_setBackgroundColor 首先创建UIV ...

  3. Runtime运行时的那点事儿

    注:本文是对 Colin Wheeler 的 Understanding the Objective-C Runtime 的翻译. 初学 Objective-C(以下简称ObjC) 的人很容易忽略一个 ...

  4. runtime 运行时机制 完全解读

    runtime 运行时机制 完全解读   目录[-] import import 我们前面已经讲过一篇runtime 原理,现在这篇文章主要介绍的是runtime是什么以及怎么用!希望对读者有所帮助! ...

  5. Runtime 运行时之一:消息传递

    什么是Runtime? Runtime顾名思义即为运行时.就是系统运行时候的一些机制,它提供了一些使得对象之间能够传递消息的重要函数,其中最主要的就是消息机制了.相较于C语言而言,C语言使用的是“静态 ...

  6. 编译器设计-RunTime运行时环境

    编译器设计-RunTime运行时环境 Compiler Design - Run-Time Environment 作为源代码的程序仅仅是文本(代码.语句等)的集合,要使其活动,它需要在目标计算机上执 ...

  7. Objective-C Runtime 运行时之四:Method Swizzling

    理解Method Swizzling是学习runtime机制的一个很好的机会.在此不多做整理,仅翻译由Mattt Thompson发表于nshipster的Method Swizzling一文. Me ...

  8. Objective-C Runtime 运行时之一:类与对象

    Objective-C语言是一门动态语言,它将很多静态语言在编译和链接时期做的事放到了运行时来处理.这种动态语言的优势在于:我们写代码时更具灵活性,如我们可以把消息转发给我们想要的对象,或者随意交换一 ...

  9. Objective-O Runtime 运行时初体验

    Objective-C语言是一门动态语言,它将很多静态语言在编译和链接时期做的事放到了运行时来处理.这种动态语言的优势在于:我们写代码时更具灵活性,如我们可以把消息转发给我们想要的对象,或者随意交换一 ...

随机推荐

  1. 【非原创】IOS 验证文字是否是中文

    从环信中找到的部分不错的代码,拿出来记录一下 是否是中文 -(BOOL)isChinese{ NSString *match=@"(^[\u4e00-\u9fa5]+$)"; NS ...

  2. Windows 10预览版14316开启Bash命令支持

    00x0 前言 4月7日凌晨,微软推送了最新的Windows 10一周年更新预览版14316,其中重要的是原生支持Linux Bash命令行支持. 00x1 问题 如何开启Linux Bash命令行? ...

  3. 【C#】ConcurrentBag<T> 方法

    转载自MSDN. ConcurrentBag<T> 类型公开以下成员. 方法     显示: 继承 保护   名称 说明 Add 将对象添加到 ConcurrentBag<T> ...

  4. eclipse里打开SWT项目找不到source/design的图形UI设计界面

    因为前天重新装了个新版的eclipse, 结果今天打开一个SWT的项目,突然找不到source/design的图形UI设计的两个切换按钮 我把SWT组件重新装了还是找不到.结果后来发现是因为重装ecl ...

  5. Windows 10 下mysql 安装后无法启动问题

    安装过程: 1. 官网下载5.15.7, http://dev.mysql.com/downloads/, 选择开源社区版:MySQL Community Server (GPL) 2. 我解压后放在 ...

  6. ZKUI中文编码以及以docker方式运行的问题

    *:first-child { margin-top: 0 !important; } body>*:last-child { margin-bottom: 0 !important; } /* ...

  7. thinkcmf开发--关于控制器

    一.安装 安装---删除install文件--删除index.php--修改数据库信息--创建数据库 修改数据库信息:\data\conf\db.php(包括服务器地址) 二.创建mobile app ...

  8. mysql NOW,CURRENT_TIMESTAMP,SYSDATE 之间的区别

    这些函数都可以返回当前的系统时间,但它们之间有什么区别呢??大家先看一下以下这个例子. select NOW(), CURRENT_TIMESTAMP(),SYSDATE(); 从上面的例子可以看出返 ...

  9. Imperva WAF使用笔记

    添加IP白名单 在对自己公司网站进行安全测试时会被WAF拦截,如果把WAF彻底停掉就无法拦截到外部的攻击了. 此时可以添加IP地址白名单,白名单内的IP对网站发起扫描时不会做拦截.

  10. 从头开始构建LINUX [LFS 脚本]

    脚本共享在这 http://pan.baidu.com/s/1nt6yiH7 version-check.sh : 这个是检查HOST机器的软件依赖情况 host-dep.sh:针对ubuntu10_ ...