问题
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();
回答1:
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
.
来源:https://stackoverflow.com/questions/9773360/entityconnection-and-opened-sqlconnection