【问题标题】:Development and Production databases开发和生产数据库
【发布时间】:2012-04-15 02:08:41
【问题描述】:

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

因此,为了避免在运行测试时受到干扰,我们希望使用不同的数据库进行测试。使用实体框架时我们如何处理第二个数据库?我们想要一个(至少)半自动的解决方案,因此我们不必在每次需要运行测试时都摆弄 Web.config。

【问题讨论】:

  • 你在说什么样的“测试”?使用部署脚本中指定的自己的数据库(通过修改 web.config)为远程团队部署单个版本有什么问题?
  • 我们正在开发 WCF Web 服务,它正在认真开发中。必须为他们部署一个独特的版本(使用他们自己的 Web.config)意味着,我们每次部署时都必须完成所有手动工作。
  • 不,不会。好像您从未听说过只设置一次并自动运行的持续集成/部署。
  • 我们确实有持续集成设置 (TeamCity),你是对的:我们可能可以配置它来这样做。但我们都不是这方面的专家。

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


【解决方案1】:

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

我会在 Visual Studio 中为您的项目创建一个新配置“测试”...它可以是您现有开发配置(或调试/发布等)的副本。然后,在解决方案资源管理器中右键单击您的 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>

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

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

【讨论】:

  • @SayedIbrahimHashimi +1,感谢他在 MS Build 和许多使我的工作更轻松的工具上“写书”的人。谢谢你。
【解决方案2】:

解决方案来自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 在编译时指定正确的连接字符串

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-18
    • 2016-01-15
    • 1970-01-01
    • 1970-01-01
    • 2018-03-17
    • 1970-01-01
    相关资源
    最近更新 更多