簡體   English   中英

Linq2DB為什么在處理DataContext后執行SQL語句

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM