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?
The entities
variable just contains a reference to the table. You should materialize your data in scope of the context, so you could do smth like
IQueryable<M> entities = null;
List<M> realEntities = null;
using (var context = new DataContext("MySql", ConnectionString))
{
entities = context.GetTable<M>();
// materialize entities in scope of the context
realEntities = entities.ToList();
}
return realEntities;
Also you could perform some filtering before the materialization:
using (var context = new DataContext("MySql", ConnectionString))
{
entities = context.GetTable<M>();
// you can apply Where filter here, it won't trigger the materialization.
entities = entities.Where(e => e.Quantity > 50);
// what exactly happens there:
// 1. Data from the M table is filtered
// 2. The filtered data only is retrieved from the database
// and stored in the realEntities variable (materialized).
realEntities = entities.ToList();
}
There is a topic about materialization I recommend you to look into.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.