asp.net - 从备用位置获取 Entity Framework 连接字符串?

标签 asp.net entity-framework web-config

如何从自定义配置文件而不是 web.config 检索 Entity Framework 4 连接字符串?

编辑: 删除默认构造函数生成的代码并在分部类中重新创建它以使用拉入的连接字符串是否合理?

我真的很想避免使用包括连接字符串在内的重载方法更改对 EF 上下文的所有引用。

@BrokenGlass:这就是我们最终得到的结果:

public partial class STARSEntities
{
    private const string _connectionStringFormat = @"metadata=res://*/STARS.EntityModel.STARSModel.csdl|res://*/STARS.EntityModel.STARSModel.ssdl|res://*/STARS.EntityModel.STARSModel.msl;provider=System.Data.SqlClient;provider connection string='Data Source={0};MultipleActiveResultSets=True'";

    /// <summary>
    /// Initializes a new STARSEntities object using the connection string found in the STARS.xml configuration file.
    /// </summary>
    /// <remarks>
    /// If the STARSEntities class is regenerated from the database, the default constructor needs to be removed from the generated file.
    /// </remarks>
    public STARSEntities() : base(GetConnectionString(), "STARSEntities")
    {
        this.ContextOptions.LazyLoadingEnabled = true;
        OnContextCreated();
    }

    private static string GetConnectionString()
    {
        return string.Format(_connectionStringFormat, ApplicationConfiguration.GetConnectionString("STARS"));
    }

}

最佳答案

DataContext 有一个构造函数重载,您可以传递连接字符串 - 在这种情况下,您可以从任何您喜欢的地方获取设置。

根据更新的问题进行编辑:

I would really like to avoid changing all references to the EF context with an overloaded method including the connection string.

问题是 T4 脚本创建的实体上下文生成一个用作连接字符串的 const 属性

    public const string ConnectionString = "name=FooEntities";

    public FooEntities()
        : base(ConnectionString, ContainerName)
    {
        this.ContextOptions.LazyLoadingEnabled = true;
    }

由于您无法覆盖分部类的默认构造函数,因此您唯一的其他选择是更改 T4 脚本本身 - 您应该在 .TT 脚本文件中看到以下内容:

    public <#=code.Escape(container)#>()
        : base(ConnectionString, ContainerName)
    {
<#
        WriteLazyLoadingEnabled(container);
#>
    }

要强制使用连接字符串,您可以修改构造函数调用,通过调用在单独文件中定义的静态方法来确定连接字符串(但对于相同的分部类 FooEntities) :

    public <#=code.Escape(container)#>()
        : base(GetCustomConnectionString(), ContainerName)
    {
<#
        WriteLazyLoadingEnabled(container);
#>
    }

现在GetCustomConnectionString()可以单独定义

public partial class FooEntities : ObjectContext
{
   public static string GetCustomConnectionString()
  {
     return "Foobar"; //however you want to determine connection string here
  }
}

你会发现这变得非常复杂和脆弱,所以我不建议这样做 - 但你可以。

关于asp.net - 从备用位置获取 Entity Framework 连接字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5226368/

相关文章:

asp.net - 在线支付系统 - 彩票申请( Stripe 禁止业务)替代方案?

c# - 将数据库 View 映射到 EF 5.0 Code First w/Migrations

asp.net-mvc - 如何在 Entity Framework 代码优先中以编程方式更新数据库?

asp.net-mvc - 从对象上下文中分离实体

asp.net-mvc - 为什么我可以从 MVC 应用程序中删除 ExtensionlessUrlHandler 而没有任何不良影响?

asp.net - .Except<T> 抛出异常

c# - JSON 安全和加密

asp.net - SSL 证书 Http 到 Https 的重定向太多

c# - 创建 URL 枚举 - 错误 : Identifer expected

asp.net - Web 应用程序项目程序集引用存储在哪里?