c# - 来自 Entity Framework 的提供程序连接字符串

标签 c# entity-framework edmx objectcontext

如果您正在使用对象上下文数据模型(带有 EDMX 文件),在创建过程中您可能需要在配置文件中指定连接字符串。

不幸的是,连接字符串不是通用连接字符串,因为它包含一些……实体连接所需的东西。 MySql 连接示例:

<add name="MyDbEntities" connectionString="metadata=res://*/Namespace.MyDb.csdl|res://*/Namespace.MyDb.ssdl|res://*/Namespace.MyDb.msl;provider=MySql.Data.MySqlClient;provider connection string=&quot;server=172.17.17.154;User Id=user;password=password;Persist Security Info=True;database=MyDatabase;Convert Zero Datetime=true&quot;" providerName="System.Data.EntityClient" />

我遇到的问题是这个连接字符串在参数“provider connection string”中包含了provider的连接字符串。

出于特定原因,我需要创建一个与实体模型无关的新 MySqlConnection。 为了创建 MySqlConnection,我需要为其提供 mysql 连接字符串 - 这是实体模型的提供程序连接字符串,我知道我需要的连接字符串始终与实体模型的连接字符串相同。

但是我如何以编程方式获取提供程序连接字符串?我一直在浏览模型实例,但没有成功......

以下内容:

ModelInstance.Connection.ConnectionString

包含类似“name=TestBotEntities”的内容,甚至不是整个连接字符串。所以我尝试了:

ConfigurationManager.ConnectionStrings["MyDbEntities"].ConnectionString

但是那个包含整个实体连接字符串,我只是不知道如何解析它,如何只从中获取提供者连接字符串。

最佳答案

事实证明有两种方法。

我可以通过 EntityConnectionStringBuilder 解析实体连接字符串:

string entityConnectionString = ConfigurationManager.ConnectionStrings["MyDbEntities"].ConnectionString;
string providerConnectionString = new EntityConnectionStringBuilder(entityConnectionString).ProviderConnectionString;

...或者如果我有可用的特定模型实例,我可以从这里获取它。

((System.Data.EntityClient.EntityConnection)ModelInstance.Connection).StoreConnection.ConnectionString;

关于c# - 来自 Entity Framework 的提供程序连接字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11840896/

相关文章:

c# - EF逆向工程代码优先和存储过程

c# - 使用 C# 访问二维数组时出错

c# - 从另一个 AppDomain 编码程序集

c# - 泛型和 Entity Framework

asp.net-mvc-3 - ASP.Net MVC 3 Entity Framework 4.1 重写 SaveChanges

sql-server - 在 edmx 中重命名列的最佳方法是什么?

c# - 如何对泛型类型使用运算符

c# - 字符串格式 : leading zeroes and no trailing zeroes

entity-framework - 使用 Entity Framework 导航属性而不创建大量查询(避免 N+1)

c# - EF Core DbSet 的 "Select"Extension 仍然显示其他列