开发和生产数据库

时间:2012-03-31 19:42:39

标签: c# entity-framework-4.1 multiple-databases slowcheetah

我和我的团队正在进行一个项目,我们正在使用Entity Framework 4.1(Code First)。我们想编写一些测试,但我们不希望它们在我们的主数据库上运行,因为我们在新加坡有一个团队为我们的工作编写客户端,并且他们不断地访问该数据库。

因此,为避免在运行测试时出现干扰,我们希望有一个不同的数据库进行测试。使用Entity Framework时,我们如何处理第二个数据库?我们想要一个半自动(至少)的解决方案,因此每次我们需要运行测试时,我们都不必乱用Web.config。

2 个答案:

答案 0 :(得分:2)

摆弄web.config可能会出现一个容易出错的进程......除非您使用的是web.config Transformations

我会在Visual Studio中为您的项目创建一个新的配置“Test”...它可以是您现有开发配置(或Debug / Release,无论如何)的副本。然后,在解决方案资源管理器中右键单击Web.config文件,然后单击添加配置转换。按照here说明操作,了解如何编写转换文件。如果您只需要更改测试环境的EF连接字符串,它将在web.Test.config中看起来像这样:

<?xml version="1.0"?>
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
<connectionStrings>
    <add name="AdventureWorksEntities" 
     connectionString="metadata=.\AdventureWorks.csdl|.\AdventureWorks.ssdl|.\AdventureWorks.msl;
     provider=System.Data.SqlClient;provider connection string='Data Source=TestDB;
     Initial Catalog=AdventureWorks;Integrated Security=True;Connection Timeout=60;
     multipleactiveresultsets=true'" providerName="System.Data.EntityClient" 
    xdt:Transform="SetAttributes" xdt:Locator="Match(name)"/>
</connectionStrings>

当您想要运行测试时,请确保在正确的配置下构建。

Configuration Manager

还有一个Visual Studio加载项SlowCheetah,它使整个过程在IDE中非常无缝。

答案 1 :(得分:1)

this帖子中删除解决方案:

//Get the connection string from app.config and assign it to sqlconnection string builder
SqlConnectionStringBuilder sb = new SqlConnectionStringBuilder(((EntityConnection)context.Connection).StoreConnection.ConnectionString);
sb.IntegratedSecurity = false;
sb.UserID ="User1";
sb.Password = "Password1";

//set the object context connection string back from string builder. This will assign modified connection string.
((EntityConnection)context.Connection).StoreConnection.ConnectionString = sb.ConnectionString;

这允许您在运行时更改连接字符串。还有其他几种可能的解决方案:

  1. 围绕连接字符串创建包装器属性。从测试中,将其设置为不同的值。
  2. 使用#IF TEST pragma在编译时指定正确的连接字符串