如何在一个项目中使用2个不同的连接字符串?

时间:2013-12-09 14:29:36

标签: c# sql-server entity-framework visual-studio

我们有一个场景,我们有两个SQL Server数据库,一个用于测试,一个用于部署。当我进入项目时,他们一直在使用类型化数据集并传递连接字符串以确定哪个数据库。两者都只有一个类型化的数据集。

现在,我正在尝试使用Entity Framework执行此操作。虽然我可以在同一个类库中有两个EDMX模型,但是catch是两个数据库具有相同的表,因此生成具有相同名称且存在冲突的相同C#类。

无论如何都要处理这种情况吗?

3 个答案:

答案 0 :(得分:5)

您要做的一件事是将webconfig文件设置为指向生产数据库服务器,当您将其设置为发布或发布时。

如果您正在调试它,那么它将指向您的开发SQL服务器。

设置非常简单,webconfig文件包含web.Release.configweb.Debug.config,您可以在此处将其设置为替换连接字符串。


  <!--
    In the example below, the "SetAttributes" transform will change the value of 
    "connectionString" to use "ReleaseSQLServer" only when the "Match" locator 
    finds an atrribute "name" that has a value of "MyDB".

    <connectionStrings>
      <add name="MyDB" 
        connectionString="Data Source=ReleaseSQLServer;Initial Catalog=MyReleaseDB;Integrated Security=True" 
        xdt:Transform="SetAttributes" xdt:Locator="Match(name)"/>
    </connectionStrings>
  -->

在您的情况下,您将放置替换属性。

答案 1 :(得分:0)

您可以获取从中派生模型的Objectcontext的重载版本,该版本将连接字符串作为参数

答案 2 :(得分:0)

对我来说,关于使用包含名称 runner 的 gitlab ci,以下内容就足够了。

public static string GetConnectionString(IConfiguration configuration)
        {
            if (Environment.MachineName.Contains("runner"))
            {
                return configuration.GetConnectionString("DatabasePipeline");
            }
            return configuration.GetConnectionString("DatabaseLocal");
        }