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();