在实体框架中使用多个连接字符串 [英] Using multiple connection strings with entity framework
问题描述
我有一个包含多个edmx文件的数据类库。
每个edmx文件因此引用不同的数据库;我有多个连接字符串。如何让我的上下文使用适当的连接字符串。例如:当我打电话给第二个edmx模型时。
我猜错了,因为选择了错误的连接字符串。我找到了EntityConnectionStringBuilder
但是,不知道如何应用它。
任何建议。
我相信你只需给它连接字符串的名称你的app / web.config文件。
使用(var context = new MyDbContext( connectionStringName ))
{
....
}
如果我没错,你可以在配置文件中设置多个连接字符串。看看这里:实体框架 - 配置文件设置 [ ^ ]和这里:实体框架 - 连接和模型 [ ^ ]
示例:
< connectionstrings >
< add name = BlogContext >
providerName =System.Data.SqlClient
connectio nString =Server = .\SQLEXPRESS; Database = Blogging; Integrated Security = True;/>
<! - 此处添加另一个连接字符串 - >
< / add > < / connectionstrings >
如何使用它?创建新的 ObjectContext [ ]使用给定的连接字符串和默认实体容器名称初始化ObjectContext类的新实例。
类似主题:
如何:从中读取连接字符串Web.config文件 [ ]
连接字符串和配置文件 [ ]
< blockquote>你可以在这里看到解决方案:
http://stackoverflow.com/questions/15092290/entity-framework-using-the-same-dbcontext-with-different-connection-strings [ ^ ]
Hi,
I have a data class library that contains multiple edmx files.
Each edmx file references a different database therefore; I have multiple connection strings. How do I get my context to use the appropriate connection string. E.g.: When I make a call to the second edmx model.
I get an error presumably, because the incorrect connection string was chosen. I found the "EntityConnectionStringBuilder"
but, not sure how to apply it.
Any suggestions.
I believe you would just give it the name of the connection string in your app/web.config file.
using (var context = new MyDbContext("connectionStringName")) { .... }
If i'm not wrong, you can set mulitiple connection strings in a config file. Have a look here: Entity Framework - Config File Settings[^] and here: Entity Framework - Connections and Models[^]
Example:
<connectionstrings> <add name="BlogContext"> providerName="System.Data.SqlClient" connectionString="Server=.\SQLEXPRESS;Database=Blogging;Integrated Security=True;"/> <!-- here add another connection string --> </add></connectionstrings>
How to use it? Creating new ObjectContext[] initializes a new instance of the ObjectContext class with the given connection string and default entity container name.
Similar subjects:
How to: Read Connection Strings from the Web.config File[]
Connection Strings and Configuration Files[]
You can see the solution here:
http://stackoverflow.com/questions/15092290/entity-framework-using-the-same-dbcontext-with-different-connection-strings[^]
这篇关于在实体框架中使用多个连接字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!