EntityConnection and Opened SqlConnection
Asked Answered
G

1

4

I've a question about EntityFramework with CodeFirst approach. Based on EntityConnection source code and documentation I can't create it with already opened SqlConnection. It requires that is should be closed. We have some different DB data layers(nHibernate,etc), and it would be good, if we can reuse the same SqlConnection between them. But seems, that EntityFramework doesn't allow to do this. I can pass closed SqlConnection to DbContext, but it isn't good for me to close connection for each DbContext.

Is there a way to reuse opened sql connection?

EDIT

After EF goes to OpenSource I was able to update it. The only line I changed is in the constructor of System.Data.Entity.Core.EntityClient.EntityConnection class.

if (connection.State != ConnectionState.Closed)
{
//throw new ArgumentException(Strings.EntityClient_ConnectionMustBeClosed);
}

After I commented throw exception, I can able to reuse existing opened SQL Connection, and after DBContext used it, it won't close it, and it was still available to other stuff.

My sample code:

var connection = new SqlConnection(connectionString);
connection.Open();

MetadataWorkspace workspace = GetWorkspace(connection); // I loaded it from the same context, and save it in memory.

EntityConnection eConnection = new EntityConnection(workspace, connection);

using(var context = new EFContext(connection, false))
{
    var someData = context.SomeTable.ToList();
}

connection.Close();
Glennglenna answered 19/3, 2012 at 15:49 Comment(2)
Di you use this constructor?Unhouse
Yes, i tried it, but it requires closed connection.Glennglenna
B
5

Passing opened connection to context is currently not supported because context internally always uses EntityConnection and if you check documentation you will see that passed store connection must be in closed state.

The workaround can be creating context prior to usage of other data access technologies and explicitly open connection

objectContext.Connection.Open();

Now you should be able to reuse SqlConnection inside the scope of the context:

var dbConnection = ((EntityConnection)objectContext.Connection).StoreConnection;

If you are using DbContext API I recommend you reading this article for additional details how to solve the problem with DbContext.

Bonaventure answered 19/3, 2012 at 18:52 Comment(1)
SqlConnection sqlConn = ((EntityConnection)objectContext.Connection).StoreConnection as SqlConnection;Aq

© 2022 - 2024 — McMap. All rights reserved.