c# - Linq2Entites Count() with condition on bool not working as "I thought it would"吗?

标签 c# linq entity-framework-4 linq-to-entities

给定以下非常简单的 linq 语句

vm.VerifiedGroups = db.ReportGroups.Count(g => g.Verified);

vm.VerifiedGroups = db.ReportGroups.Count(g => g.Verified == true);

Verified 是一个 bool 值,我得到一个异常,说这不受 linq-2-entities 支持?

错过了一些非常简单的东西 - 或者我应该从中选择一个:

a)
vm.VerifiedGroups = db.ReportGroups.Where(g => g.Verified).Count();

b)
vm.VerifiedGroups = db.ReportGroups.ToList().Count(g => g.Verified);

这两个都有效(我的列表只有 30-50 长,所以 ToList 不是问题)。

最佳答案

你没有错过任何东西。 Linq to Entitities 不支持使用谓词计数。参见 msdn 文章 Supported and Unsupported LINQ Methods (LINQ to Entities)

是的,您应该选择第一个选项,因为 ToList() 将执行查询并将所有实体存入内存:

vm.VerifiedGroups = db.ReportGroups.Where(g => g.Verified).Count();

即使您的 ReportGroups 表中没有很多记录,您为什么要做一些速度较慢且使用更多 pc、数据库和网络资源的事情?比较传输一个整数值与传输 50 个 ReportGroup 实体的所有字段,从 DataReader 创建 .net 对象(并保持连接打开),并迭代创建的列表,执行谓词方法在每个 DataReader 实体上。我认为在这里传输一个整数值会获胜。

关于c# - Linq2Entites Count() with condition on bool not working as "I thought it would"吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14335230/

相关文章:

c# - 如何从我的 App_Themes 文件夹中列出可用的 Css 类?

linq - 如何在Linq中进行简单的计数?

c# - 您知道哪些使用 Entity Framework 和 DbContext 的模式和实践?

c# - 将数据列添加到数据表

c# - 查找一行中具有相同值的单元格数,然后存储这些坐标

c# - 随 secret 码生成器

c# - 使用大量小 XML 文件使 LINQ 的文件 IO 更高效?

c# - LINQ 中的分层查询

c#-4.0 - 类型 'X' 未映射为表

c# - 如何使用 Entity Framework 4 为多语言数据库中的 POCO 对象建模?