将sql查询与EF查询进行映射;不起作用
本文关键字:查询 映射 不起作用 EF sql | 更新日期: 2023-09-27 18:28:54
我正在尝试使用EF6执行查询。我的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
向致以最良好的问候
对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();
您不应该使用Count<TSource>(IEnumerable<TSource>, Func<TSource, Boolean>)
,因为它是
返回一个数字,表示指定序列中有多少元素满足条件来源
i=>i.SUBJECT
是Func<TSource, String>
,但该方法需要Func<TSource, Boolean>
,这就是您收到该异常消息的原因。
相反,使用Count<TSource>(IEnumerable<TSource>)
,它将返回序列中元素的总数,例如:
Count = m.Count().ToString()