【发布时间】:2015-06-09 00:41:13
【问题描述】:
我们处于一个混合环境中,我们的应用程序同时使用 ADO.NET 和 Entity Framework。
由于两者都指向同一个物理 SQL 服务器,我们希望从配置文件中删除 Entity Framework 连接字符串,然后根据当前的 ADO.NET 连接字符串自动构建字符串。
这使我们避免了开发人员更改 ADO.NET 字符串但忘记更改实体框架连接字符串的错误。
我已阅读此内容,但他们没有回答问题。
How do I create connection string programmatically to MS SQL in Entity Framework 6?
如果我创建自己的 DbConnection 并将其传递给 DbContext(existingConnection, contextOwnsConnection),则会引发错误“上下文正在代码优先模式下使用,代码是从数据库优先或模型的 EDMX 文件生成的第一次开发。”
我没有使用 Code First。
https://msdn.microsoft.com/en-us/data/jj680699
这谈到了 EF 6 中的代码库配置,但文章没有显示任何实际更改连接字符串的代码。
更新:更多信息有助于澄清我的问题。
我没有先使用代码,而是想在配置文件之外构建一个连接字符串。
我使用的 DbContext 是 T4 模板正在生成的自动生成的 DbContext 文件的部分类。
我的印象是我需要创建一个继承的 DbConfiguration 类并在该类中执行某些操作,但我发现的唯一示例是使用 Azure。
https://msdn.microsoft.com/en-us/data/jj680699
代码项目上有一篇文章谈到了在运行时设置连接字符串,但这篇文章是基于每次创建新实体容器时构建连接字符串。
http://www.codeproject.com/Tips/234677/Set-the-connection-string-for-Entity-Framework-at
我希望能够使用我的部分 DbContext 类来创建连接字符串,这样调用者就不必做任何特殊的事情。
更新:RunTime 的工作代码,但 DesignTime 的工作代码
使用@Circular Reference“下面列出”发布的代码,我能够在不更改对我的实体类的调用的情况下更改连接字符串,但这不适用于 DesignTime EDMX 文件。
public partial class TestEntities : DbContext
{
public TestEntities() : base(GetSqlConnection(), true)
{
}
public static DbConnection GetSqlConnection()
{
// Initialize the EntityConnectionStringBuilder.
EntityConnectionStringBuilder entityBuilder = new EntityConnectionStringBuilder();
var connectionSettings = ConfigurationManager.ConnectionStrings("Current_ADO_Connection_In_Config");
// Set the provider name.
entityBuilder.Provider = connectionSettings.ProviderName;
// Set the provider-specific connection string.
entityBuilder.ProviderConnectionString = connectionSettings.ConnectionString;
// Set the Metadata location.
entityBuilder.Metadata = "res://*/Models.TestModel.csdl|res://*/Models.TestModel.ssdl|res://*/Models.TestModel.msl";
return new EntityConnection(entityBuilder.ToString());
}
}
现在,如果我能让 DesignTime 正常工作,那就太好了。
【问题讨论】:
-
我认为您将使用 ObjectContext 而不是 DbContext,因为您没有使用 Code First。我对这段关系不是 100% 确定的。这暗示了这一点:msdn.microsoft.com/en-us/library/bb738461(v=vs.110).aspx 并从此处链接描述创建连接:msdn.microsoft.com/en-us/library/…
-
CodeFirst 的连接字符串通常是标准连接字符串,而非 CodeFirst 的连接字符串通常是对 csdl/ssdl/msl 文件的引用。
-
你可以使用ObjectContext,但是如果你不需要深入研究它的特殊属性,那就很麻烦了。从 EF 5 开始,使用 DbContext 是正常的。 EntityConnection 是常规连接字符串的超集,具有访问 EDMX 文件的概念和存储部分的附加属性。
标签: .net entity-framework entity-framework-6