用于需要动态获取链接字符串(比如从配置中心)获取数据源地址然后链接数据库的情形,需要在服务器上配置MSDTC。
以下是动态链接数据库的代码
using (var ctx = new YourDbContextWhereCanFindConnectionString()) {
...
var record = "your code to find the connection string record";
DbConnectionStringBuilder cb = new DbConnectionStringBuilder();
cb.ConnectionString = record.DbConnString;
cb["MultipleActiveResultSets"] = true;
cb["App"] = "EntityFramework";
return new TheDbContextBeingConnectedDynamically(cb.ToString());
...
}
MSDTC配置
1. 打开防火墙配置选择 Advanced Settings
或者在Server Manager, 选择 Tools, 选择 Windows Firewall with Advanced Security.
右键 Inbound Rules, 选择 New Rule.
选择 Program 然后 Next.
输入 program path : %SystemRoot%\system32\msdtc.exe, 下一步
Allow the connection,下一步.
选择 Domain, 下一步
输入名称, 如 MSDTC ,完成。