是否可以从不同的连接字符串加载相同的上下文?

时间:2016-04-14 03:15:08

标签: c# entity-framework

是否可以从不同的连接字符串加载到相同的上下文中?

我有4个相同的数据库。结构相同但每个都包含特定数据。我有上下文。

 Namespace.Data.dbContext dbContext_1 = new Namespace.Data.dbContext();
 Namespace.Data.dbContext dbContext_2 = new Namespace.Data.dbContext();
 Namespace.Data.dbContext dbContext_3 = new Namespace.Data.dbContext();
 Namespace.Data.dbContext dbContext_4 = new Namespace.Data.dbContext();

但在我的配置文件中我有这个

<add name="dbContext_1" connectionString="..." providerName="System.Data.EntityClient" /> 
<add name="dbContext_2" connectionString="..." providerName="System.Data.EntityClient" /> 
<add name="dbContext_3" connectionString="..." providerName="System.Data.EntityClient" /> 
<add name="dbContext_4" connectionString="..." providerName="System.Data.EntityClient" /> 

我得到一个例外,因为Entity Framework告诉我它没有找到dbContext的连接字符串。

默认情况下,EF加载一个带有类名的连接字符串。正确?如何使其加载其他连接字符串?

1 个答案:

答案 0 :(得分:1)

DbContext有一个重载,允许您指定要使用的连接字符串或连接字符串名称。

public class YourContext : DbContext
{
    // You can pass either dbContext_1, dbContext_2, dbContext_3, dbContext_4 as connection string name
    public YourContext(string nameOrConnectionString) 
        : base(nameOrConnectionString)
    {
    }
}

如果您的上下文没有此重载,则您必须更新T4模板才能添加它。在模板中找到此部分:

<#=Accessibility.ForType(container)#> partial class <#=code.Escape(container)#> : DbContext
{        
    // This will generate the default constructor    
    public <#=code.Escape(container)#>()
        : base("name=<#=container.Name#>")
    {
<#
if (!loader.IsLazyLoadingEnabled(container))
{
#>
        this.Configuration.LazyLoadingEnabled = false;
<#
}
#>
    }

    // Removed this part for readability
}

然后修改它以添加您需要的重载。

<#=Accessibility.ForType(container)#> partial class <#=code.Escape(container)#> : DbContext
{        
    // This will generate the default constructor    
    public <#=code.Escape(container)#>()
        : this("name=<#=container.Name#>")
    {
    }

    // This is the overload you need
    public <#=code.Escape(container)#>(string nameOrConnectionString)
        : base(nameOrConnectionString)
    {
<#
if (!loader.IsLazyLoadingEnabled(container))
{
#>
        this.Configuration.LazyLoadingEnabled = false;
<#
}
#>
    }

    // Removed this part for readability
}

有了这个,您应该能够告诉您的数据库连接的上下文。