Many queries and too much opening / closing of the same connection

為{幸葍}努か 提交于 2019-12-05 07:17:10

It is possible to create a context with an existing connection. It's hard to find documentation about it, but if the connection is opened explicitly before the context uses it, it will stay open until it is explicitly closed or disposed. I tested this with an EF5 ObjectContext (Linqpad code):

using (var conn = new EntityConnection(connectionString))
{
    conn.Open();
    using (var db = new InventoryContext(conn))
    {
        db.Products.ToList();
        conn.State.Dump();
        db.SaveChanges();
        conn.State.Dump();
    }
}

The output is Open, Open. When the connection is not opened the output is Closed, Closed.

Another solution could be to open the connection when the DbContext is constructed:

public partial class QueryModel : DbContext
{
    public QueryModel(string connectionName):base(connectionName)
    {
        this.Database.Connection.Open();
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!