Search code examples
c#sqllinq-to-sqldeferred-executionlinq2db

Why is Linq2DB executing SQL-Statement after disposing DataContext


I have tested the following code with Linq2DB:

IQueryable<M> entities = null;

using (var context = new DataContext("MySql", ConnectionString))  
{
    entities = context.GetTable<M>();
}

var list = entities.ToList();

return entities;

I wonder why the query at entities.ToList() is executed even though the DataContext was disposed?


Solution

  • That's how DataContext is designed (compared to DataConnection context implementation). By default it acquires connection only for single query (or transaction, if you use it), and releases it back to pool after query executed/transaction completed/disposed, so it is safe.

    Another situation will be if you will set KeepConnectionAlive to true. I suspect in this case we will have connection leak, so I will fill issue for it.