[英]Why is Linq2DB executing SQL-Statement after disposing DataContext
我已經使用Linq2DB測試了以下代碼:
IQueryable<M> entities = null;
using (var context = new DataContext("MySql", ConnectionString))
{
entities = context.GetTable<M>();
}
var list = entities.ToList();
return entities;
我想知道為什么即使處理了DataContext
執行entities.ToList()
處的查詢?
entities
變量僅包含對該表的引用。 您應該在上下文范圍內實現數據,這樣您就可以做到
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;
您也可以在實現之前執行一些過濾:
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();
}
我建議您研究一個有關實現的主題 。
這就是DataContext
的設計方式(與DataConnection
上下文實現相比)。 默認情況下,它僅獲取單個查詢(或事務(如果使用的話))的連接,並在查詢執行/事務完成/處置后將其釋放回池中,因此是安全的。
另一種情況是將KeepConnectionAlive
設置為true
。 我懷疑在這種情況下,我們會發生連接泄漏,因此我將為此填充問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.