如何将 ADO.net 实体框架与现有的 SqlConnection 一起使用? [英] How to use ADO.net Entity Framework with an existing SqlConnection?

查看:26
本文介绍了如何将 ADO.net 实体框架与现有的 SqlConnection 一起使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  1. 我有一个使用 SqlConnection 的现有 asp.net 网站.
  2. 我已添加 ADO.net 实体框架.
  3. 我已成功连接到数据库并创建了 .edmx 文件.
  4. 我能够通过 Entity Framework 使用自动生成的连接字符串进行连接.

我想使用我在整个站点中使用的现有 SqlConnection 对象进行实体框架连接.
我不想为要使用 ADO.net Entity Framework 的一个页面使用第二个数据库连接,也不想更改整个站点以使用新的 Entity Framework 连接字符串.

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.

推荐答案

那个论坛帖子有答案:

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 映射文件的位置——在这种情况下是当前程序集中的嵌入资源.

"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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆