19
  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.

EZ.
  • 223
  • 1
  • 5
  • 10

3 Answers3

23

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.

Andrew Peters
  • 11,135
  • 4
  • 37
  • 34
  • 2
    Thanks, Now I get this error: MetadataWorkspace must have EdmItemCollection pre-registered. The project is an Asp.net Web page with an .edmx file. I think its not getting the data from the .edmx file. – EZ. Feb 06 '09 at 18:49
  • 3
    i had the same problem but you change Assembly.GetExecutingAssembly() to Assembly.GetAssembly(typeof(NorthwindEntities)) it got it working nicely. – Hath Dec 10 '09 at 12:48
  • 1
    Changing the assembly to Assembly.GetAssembly(typeof(NorthwindEntities)) did not work for me. – Kyle Apr 15 '14 at 18:17
1

You can do this by using the constructor of your generated ObjectContext that accepts an EntityConnection. When you create the EntityConnection you pass in your SqlConnection.

Andrew Peters
  • 11,135
  • 4
  • 37
  • 34
  • I have been going around and around with the System.Data.EntityClient.EntityConnection. It’s right there at my finger tips but I cannot seem to get the MetadataWorkspace parameter to work. – EZ. Feb 06 '09 at 05:57
1

Andrew Peters,

Thank you for your answer.

I have been going around and around with the System.Data.EntityClient.EntityConnection.

It’s right there at my finger tips but I cannot seem to get the MetadataWorkspace parameter to work.

This is the closest example I have found (the post marked Answer):

http://social.msdn.microsoft.com/Forums/en-US/adodotnetentityframework/thread/dd7b1c41-e428-4e29-ab83-448d3f529ba4/

Thanks for any help.

EZ.
  • 223
  • 1
  • 5
  • 10