我正在尝试使用EF6 .my查询以sql格式执行查询,如下所示:
/****** Script for SelectTopNRows command from SSMS ******/
SELECT
[SUBJECT],COUNT(SUBJECT)
FROM [PGC].[dbo].[QC] group by [SUBJECT]
效果很好。
主题是字符串类型。
但是我将查询翻译成EF,你可以在这里看到:
listDataSource =
db.QCs.Where(j => j.SUBJECT != null).ToList().GroupBy(i => new {i.SUBJECT}).Select(m => new chart()
{
date = m.Key.SUBJECT,
Count = m.Count(i=>i.SUBJECT).ToString()
}).ToList();
m.Count(i => i.SUBJECT)会返回错误:can't convert expression type string to return type bool
最好的问候
答案 0 :(得分:1)
您不应该使用Count<TSource>(IEnumerable<TSource>, Func<TSource, Boolean>)
因为它:
返回一个数字,表示指定序列中有多少元素满足条件。Source
i=>i.SUBJECT
是Func<TSource, String>
,但该方法需要Func<TSource, Boolean>
,这就是您收到该异常消息的原因。
而是使用Count<TSource>(IEnumerable<TSource>)
来返回序列中元素的总数,例如:
Count = m.Count().ToString()
答案 1 :(得分:1)
延伸Yuriy的答案(这是完全可以接受的),有几个修复,主要是为了表现:
listDataSource = db.QCs
.Where(j => j.SUBJECT != null)
.GroupBy(i => i.SUBJECT) //no need to create an anonymous type, you don't use it afterwards
.Select(group => new { SUBJECT = group.Key, Count = group.Count()}) //counting in SQL is faster
.AsEnumerable() //materialization, all the heavy lifting is performed by SQL until now
.Select(value => //seems redundant, but the previous selection just translates into an SQL select statement with SUBJECT and Count columns
new chart
{
date = value.SUBJECT,
Count = value.Count.ToString()
})
.ToList();