EntityConnection and Opened SqlConnection

不问归期 提交于 2020-01-01 12:43:09

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!