如何使用ADO.net实体框架与现有的SqlConnection? [英] How to use ADO.net Entity Framework with an existing SqlConnection?
问题描述
我想使用我在整个网站中使用的现有SqlConnection对象进行实体框架连接。
我不想要使用第二个数据库连接的一个页面将要使用ADO.net实体框架,我不想更改整个网站使用新的实体框架连接字符串。
感谢您提供的任何帮助。
该论坛帖子有答案: / p>
MetadataWorkspace workspace = new MetadataWorkspace(
new string [] {res:// * /},
new Assembly [] { Assembly.GetExecutingAssembly()});
using(SqlConnection sqlConnection = new SqlConnection(connectionString))
using(EntityConnection entityConnection = new EntityConnection(workspace,sqlConnection))
using(NorthwindEntities context = new NorthwindEntities(entityConnection) )
{
foreach(var product in context.Products)
{
Console.WriteLine(product.ProductName);
}
}
res:// * /的EF连接字符串,用于描述xml映射文件的位置 - 在本例中为当前程序集中嵌入的资源。
- I have an existing asp.net website that uses an SqlConnection.
- I have added the ADO.net Entity Framework.
- I have successfully connected to the database and created the .edmx file.
- I am able to connect through the Entity Framework with the connectionstring that is automatically generated.
I want to use the existing SqlConnection object that I use throughout the site for the Entity Framework connection.
I do not want to have to use a second database connection for the one page that is going to use the ADO.net Entity Framework and I don’t want to change the entire site to use the new Entity Framework connection string.
Thanks for any help you can provide.
That forum post has the answer:
MetadataWorkspace workspace = new MetadataWorkspace(
new string[] { "res://*/" },
new Assembly[] { Assembly.GetExecutingAssembly() });
using (SqlConnection sqlConnection = new SqlConnection(connectionString))
using (EntityConnection entityConnection = new EntityConnection(workspace, sqlConnection))
using (NorthwindEntities context = new NorthwindEntities(entityConnection))
{
foreach (var product in context.Products)
{
Console.WriteLine(product.ProductName);
}
}
"res://*/" is the part of your EF connection string that describes the location of your xml mapping files - in this case embedded resources in the current assembly.
这篇关于如何使用ADO.net实体框架与现有的SqlConnection?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!