entity-framework - DbContext 释放后枚举成功

标签 entity-framework linq-to-entities

背景

我正在根据父/子关系创建投影,其中包括父项的 Name 属性和子项的 Id 列表。

代码

private class ParentChildInfo
{
    public string Name { get; set; }
    public List<int> ChildIds { get; set; }
}

var infos = ctx.Masters.Include(m => m.Children).Select(
    m => new ParentChildInfo()
    {
        Name = m.Name,
        ChildIds = m.Children.Where(c => c.SomeProp.StartsWith("SpecialValue"))
                    .Select(c => c.Id).ToList()
    }).ToList();

不幸的是,这产生了错误

LINQ to Entities does not recognize the method 'System.Collections.Generic.List`1[System.Int32] ToList[Int32]

这引导我到 this post ,建议 ( in the comments ) 进行以下更改:

private class ParentChildInfo
{
    public string Name { get; set; }
    public IEnumerable<int> ChildIds { get; set; } // No longer List<int>
}

var infos = ctx.Masters.Include(m => m.Children).Select(
    m => new ParentChildInfo()
    {
        Name = m.Name,
        ChildIds = m.Children.Where(c => c.SomeProp.StartsWith("SpecialValue"))
                    .Select(c => c.Id) // Dropped the .ToList()
    }).ToList();

我最初想要获取列表而不是枚举,因为使用结果的代码运行了几分钟,而且我不想将 DbContext 占用那么长时间。

我使用这样的代码:

using (MyContext ctx = new MyContext())
{
    // code from above that populates infoes
}

foreach (var info in infoes)
{
    // use info.ChildIds
}

我计划移动 foreach进入using这样我就可以枚举 ChildId,但按 F5 并惊讶地发现代码有效。

问题

假设 DbContext 在此时已被处置,并且 ChildIds 是 IEnumerable<int>而不是List<int> ,为什么我可以枚举 ChildIds?

最佳答案

这是因为ToList() infos的query 实际上执行查询。所以收藏ctx.Masters被枚举并填充投影。即使没有 Include它会注意到 Master.Children被寻址并发出 SQL 连接。 IEnumerable<int> ChildIds的实现类型可能是List<int> .

关于entity-framework - DbContext 释放后枚举成功,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15667634/

相关文章:

c# - IQueryable<T>.Include() 被忽略

c# - 需要包含()相关实体但没有选择这样做

c# - Linq to Entities 奇怪的部署行为

.net - 带有时态数据库的 Entity Framework

c# - 首先在 EF6 db 中模拟数据库

c# - 帮助将 SQL 转换为 LINQ-to-Entities

c# - LINQ to Entities 条件语句给出奇怪的结果

c# - 使用数据库日期时间

php - 如何更改 symfony 2 doctrine 映射器以使用我的自定义目录而不是包下的实体目录

c# - 如何在桌面应用程序中使用 DbContext 和 DI?