为什么 Linq2DB 在处理 DataContext 后执行 SQL-Statement

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;

我想知道为什么 entities.ToList() 处的查询在 DataContext 被处理后仍然执行?

entities 变量仅包含对 table 的引用。您应该在上下文范围内具体化您的数据,这样您就可以像

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();
}

有一个 topic 关于物化我建议你看看。

这就是 DataContext 的设计方式(与 DataConnection 上下文实现相比)。默认情况下,它只为单个查询(或事务,如果你使用它)获取连接,并在查询后将其释放回池中 executed/transaction completed/disposed,所以它是安全的。

另一种情况是,如果您将 KeepConnectionAlive 设置为 true。我怀疑在这种情况下我们会发生连接泄漏,所以我会解决这个问题。