【发布时间】:2019-12-03 09:54:41
【问题描述】:
我正在尝试将 sql server 查询转换为 Mongo C# driver LINQ。
我有一个表,每个 guid 都有多个条目,每个条目都有不同的 code 值。
我需要为每个代码获取不同的 guid 计数。我可以在 LINQ 中执行 Count(),但是当我执行 Distinct().Count() 时,出现以下异常:
不支持指定的方法
以下是我要转换的 T-SQL:
SELECT a.code, substring(convert(varchar, a.create_Date, 107), 1, 6) as create_Date,count(distinct a.guid) as mycount
FROM table1 a (nolock)
WHERE a.code = 0
AND a.create_Date BETWEEN DateAdd(day, -2 , @startDate) AND DateAdd(day, 1, @startDate)
GROUP BY a.code, substring(convert(varchar, a.create_Date, 107), 1, 6)
Order by 1
以下是我的 LINQ:
var result = from tb in collection3.AsQueryable()
where
tb.code == 0
&& tb.create_Date > rptGte
&& tb.create_Date < rptLt
group tb by new
{
tb.code,
create_Date = tb.create_Date.DayOfYear
} into g
select new
{
code = g.Key.code,
create_Date = g.Key.create_Date,
mycount = g.Select(x => x.guid).Distinct().Count() //distinct not working here
};
var resultList = rpt.ToList();
请告诉我在这里做错了什么。
【问题讨论】:
-
我建议考虑使用聚合来实现这一点:docs.mongodb.com/manual/aggregation
标签: c# mongodb linq mongodb-.net-driver mongodb-csharp-2.0