Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use ADO.net Entity Framework with an existing SqlConnection?

  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.

like image 930
EZ. Avatar asked Feb 05 '09 23:02

EZ.


People also ask

Can we use ADO.NET and Entity Framework?

Entity Framework is the development of data-oriented applications using ADO.NET. Entity Framework solves problems in entity models, relationships, and business logic. Also, it works with data engines. This means Entity Framework is an Object-Relational Mapping (ORM) framework.

Can I use ADO.NET with ASP NET core?

Attachments: Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

How do I add ado net entity data model?

Create the ADO.NET Entity Data ModelRight-click on your project in the Solution Explorer window and select the menu option Add -> New Item. In the Add New Item dialog, select the Data category. Select the ADO.NET Entity Data Model template, give the Entity Data Model the name Northwind. edmx, and click the Add button.

Which database is the ADO.NET SqlConnection object?

To connect to Microsoft SQL Server, use the SqlConnection object of the . NET Framework Data Provider for SQL Server. To connect to an OLE DB data source, use the OleDbConnection object of the .


1 Answers

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.

like image 186
Andrew Peters Avatar answered Oct 07 '22 01:10

Andrew Peters