0

我已经用 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处理了查询也会执行?

4

2 回答 2

1

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

我建议您研究一个关于物化的主题。

于 2019-09-03T21:40:55.827 回答
0

DataContext就是设计的方式(与DataConnection上下文实现相比)。默认情况下,它只为单个查询(或事务,如果你使用它)获取连接,并在查询执行/事务完成/处置后将其释放回池,因此它是安全的。

另一种情况是,如果您将设置KeepConnectionAlivetrue. 我怀疑在这种情况下我们会有连接泄漏,所以我会为它填写问题。

于 2019-09-04T07:53:00.440 回答