我们有一个Entity framework 4.1设置,自动生成的POCO和DbContext类,用于与db进行交互。
自动生成的DbContext派生类如下所示:
public MyEntities()
: base("name=MyEntities")
{
}
app.config中自动生成的连接字符串类似于:
<connectionStrings>
<add name="MyEntities" connectionString="blah blah blah" providerName="System.Data.EntityClient" />
</connectionStrings>
这一切都很好,开箱即用。
我们的每个开发人员都有自己的SQL Developer版本安装,用于单元测试和开发目的,因此他们需要在进行单元测试时修改连接字符串以指向其安装。这些连接字符串位于单元测试项目的App.config文件中
目前这是一个手动修改步骤,我曾想过以某种方式自动化。
现在,我可以在代码中找出连接字符串,但是上面的默认自动生成的“MyEntities”构造函数阻止了将它传递给实体框架构造函数 - 它没有任何连接字符串参数构造函数。 (虽然DbContext确实如此)。此外,我并不特别想通过DAL代码检测连接字符串,直到实体框架代码 - 这在生产中是不需要的,因此仅仅为了单元测试而修改我的代码。
我原以为必须有一些方法来覆盖App.config中的字符串。
这与使用本地Appsettings文件完成此操作类似。
(ie <appSettings file="Local.config"/>)
,但我似乎无法看到如何为ConfigurationManager.ConnectionStrings条目执行此操作。
那么,人们在这做什么?
答案 0 :(得分:3)
如果命名约定不可接受,您可能希望在每个开发人员计算机上创建一个SQL别名,以指向他们自己的SQL实例。 本文:http://www.mssqltips.com/sqlservertip/1620/how-to-setup-and-use-a-sql-server-alias/提供了创建别名的分步说明。
答案 1 :(得分:2)
谢谢,这是我最终做的,受到以下方面的启发:
因为这仅适用于DAL单元测试而非生产,所以我会根据用户环境变量动态修改连接字符串。
我永远不会建议你进行制作,你应该使用适当的变换等。
因此,对于单元测试,我在app.configs中定义了“数据源= ENVVARTOSQLSERVER”。
然后单元测试中的fn修改配置,保存并在启动时重新加载。
private static void ModifyUnitTestConnectionString()
{
// Note that the updated .NET 2.0 and later "ConfigurationManager.ConnectionStrings"
// cannot be used to modify or add connection strings, as it is read only.
// However, accessing the same settings via the configurationSection directly
// is not read only.
// Get current configuration.
Configuration currentconfiguration =
ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
// Get the connection strings section
ConnectionStringsSection currentConnectionStringsSection =
currentconfiguration.ConnectionStrings;
// Read the "SiteEntities" connection string.
string ntCNStr =
ConfigurationManager.ConnectionStrings["MyEntities"].ConnectionString;
// Replace any instances of "ENVVARTOSQLSERVER" in that connection string
// with the appropriate environment variable.
EntCNStr = EntCNStr.Replace("ENVVARTOSQLSERVER",
Environment.GetEnvironmentVariable("ENVVARTOSQLSERVER"));
// Write the connection string and save the changed config file.
currentconfiguration.ConnectionStrings
.ConnectionStrings["MyEntities"].ConnectionString = siteEntCNStr;
currentconfiguration.Save(ConfigurationSaveMode.Minimal);
// This is this needed to refresh the configuration manager and get it to
// read the config file again.
ConfigurationManager.RefreshSection("connectionStrings");
}
所以,就是这样。 开发人员需要设置一个环境变量,以便适当的SQL源路径到位。