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

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

问题描述


  • 我有一个使用SqlConnection的现有asp.net网站。

  • 我添加了ADO.net实体框架。

  • 我已经成功连接到数据库并创建了.edmx文件。

  • 我可以通过实体框架连接自动生成的连接字符串。 >

    我想使用我在整个网站中使用的现有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映射文件的位置 - 在本例中为当前程序集中嵌入的资源。


    1. I have an existing asp.net website that uses an SqlConnection.
    2. I have added the ADO.net Entity Framework.
    3. I have successfully connected to the database and created the .edmx file.
    4. 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屋!

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