从备用位置获取实体框架连接字符串?

发布于 2024-10-21 03:52:16 字数 1253 浏览 3 评论 0原文

如何从自定义配置文件而不是 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"));
    }

}

How can I retrieve the Entity Framework 4 connection string from a custom config file, not web.config?

Edit:
Is it reasonable to delete the default constructor generated code and recreate it in a partial class to use the pulled in connection string?

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

@BrokenGlass: This is what we ended up with:

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"));
    }

}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

淤浪 2024-10-28 03:52:16

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

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

我真的很想避免改变
对 EF 上下文的所有引用
一个重载方法,包括
连接字符串。

问题是 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);
#>
    }

要强制使用连接字符串,您可以修改构造函数调用,通过调用您在单独文件中定义的静态方法来确定连接字符串(但对于相同的分部类 < code>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
  }
}

您会发现这很快变得复杂且脆弱,所以我不建议这样做 - 但您可以。

There's a constructor overload for DataContext that you can pass a connection string - in that case you can take the setting from anywhere you like.

Edit based on updated question:

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

The problem is that the Entities context created by the T4 script generates a const property that is used as connection string

    public const string ConnectionString = "name=FooEntities";

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

Since you can't override the default constructor of the partial class, your only other option would be to change the T4 script itself - you should see the following in your .TT script file:

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

To force your connection string to be used you could modify the constructor call to determine the connection string by calling a static method that you define in a separate file (but for the same partial class FooEntities):

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

Now GetCustomConnectionString() can be defined separately

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

You see this is getting complicated and fragile very fast, so I would not advise doing this - but you could.

酷炫老祖宗 2024-10-28 03:52:16

不知道这是否是您所要求的,但您可以使用connectionStrings元素的“configSource”属性:

<connectionStrings configSource="connection.config">
</connectionStrings>

Don't know if this is what you ask for, but you can use the "configSource" attribute of the connectionStrings element:

<connectionStrings configSource="connection.config">
</connectionStrings>
罗罗贝儿 2024-10-28 03:52:16

也许是这样的?

// replace the following line with any business logic you need to get to the file
// with your connection string. If it is a config-style file, you can use the 
// Frameworks's helper classes as well
string connectionString= File.ReadAllText("alternative path");
Entities ent = new Entity(connectionString);

这是Microsoft Connect 上的帖子< /a> 解释了这一点。

Something like this perhaps?

// replace the following line with any business logic you need to get to the file
// with your connection string. If it is a config-style file, you can use the 
// Frameworks's helper classes as well
string connectionString= File.ReadAllText("alternative path");
Entities ent = new Entity(connectionString);

Here's a post on Microsoft Connect that explains this.

坐在坟头思考人生 2024-10-28 03:52:16

您能够从此自定义配置文件中读取连接字符串吗?如果是这样,您可以使用采用 ConnectionString 的 DataContext 构造函数

NorthWindDataContext nwdc = new NorthWindDataContext(alternateConnectionString);

Are you able to read the connection string from this custom config file? if so, you can use the constructor for your DataContext that takes ConnectionString.

NorthWindDataContext nwdc = new NorthWindDataContext(alternateConnectionString);
别挽留 2024-10-28 03:52:16

您可以使用EntityConnectionStringBuilder:

var ecb = new EntityConnectionStringBuilder();
ecb.Metadata = "res://*/Model.MyModel.csdl|res://*/Model.MyModel.ssdl|res://*/Model.MyModel.msl";
ecb.Provider = "System.Data.SqlClient";
ecb.ProviderConnectionString = connectionStringFromFancySource;
return new MyModel(ecb.ToString());

You can use EntityConnectionStringBuilder:

var ecb = new EntityConnectionStringBuilder();
ecb.Metadata = "res://*/Model.MyModel.csdl|res://*/Model.MyModel.ssdl|res://*/Model.MyModel.msl";
ecb.Provider = "System.Data.SqlClient";
ecb.ProviderConnectionString = connectionStringFromFancySource;
return new MyModel(ecb.ToString());
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文