0

我有一个 sql 查询,想把它转换成 linq

 SELECT CAST([Date] AS DATE),
 COUNT([ID]) AS 'Amount of Systems'
 FROM [DemoDB].[dbo].[Servers]
 WHERE [ServerID] IN ('ServerX') AND [Type] = 'Complete'  
 GROUP BY CAST([Date] AS DATE)
 ORDER BY CAST([Date] AS DATE) 

这将返回结果如下

在此处输入图像描述

我试过的

 //fromDP and toDP are the names of the Datepicker's
 var query = (this.db.Servers
                     .Where(x => x.Date >= fromDP.SelectedDate.Value && 
                     x.Date <= toDP.SelectedDate.Value));


 var query_Success = query.Count(p => p.Type == "Complete" 
                     && (p.ServerID == "ServerX"));     

并且我将结果作为整体计数(例如,如果我选择从 April 1st 到 April 15th ,结果是所有“完成”的总和),但我需要在这个选定范围内的每一天计数。结果我将绑定到柱形图。如何进行 ?

4

3 回答 3

2
this.db.Servers.Where(s => s.ServerId == "ServerX" && s.Type == "Complete")
       .GroupBy(s => s.Date)
       .OrderBy(s => s.Key)
       .Select(g => new { Date = g.Key, AmountOfSystems = g.Count() });

将 Where 子句更改为

Where(s => s.ServerId == "ServerX" && s.Type == "Complete" && s.Date >= fromDP.SelectedDate.Value && s.Date <= toDP.SelectedDate.Value)

过滤到有限的日期范围。

编辑

正如@vvs0205 建议的那样。使用 EntityFunctions 类随意操作日期列:http: //msdn.microsoft.com/en-us/library/system.data.objects.entityfunctions.aspx

于 2013-05-03T10:17:53.363 回答
2

如果我理解正确,作者只想使用没有时间的日期。要使用 EF 做到这一点,我们可以使用EntityFunctions.TruncateTime修剪时间部分的方法。我将建立在@steaks 的回答:

db.Servers.Where(s => s.ServerId == "ServerX" && s.Type == "Complete")
            .GroupBy(s => EntityFunctions.TruncateTime(s.Date))
            .OrderBy(s => s.Key)
            .Select(g => new {Date = g.Key, AmountOfSystems = g.Count()});
于 2013-05-03T10:33:21.100 回答
1

像这样的东西

var fromDate = fromDP.SelectedDate.Value;
var toDate= toDP.SelectedDate.Value;

var q = from server in this.db.Servers
                where (server.Date >= fromDate && server.Date<=toDate && server.ServerID="ServerX" && server.Type=="Complete")
                group server  by server.Date
                into g
                orderby g.Key
                select new
                    {
                        Date = g.Key,
                        Count = g.Count()
                    };

var results = q.ToList();
于 2013-05-03T10:19:18.783 回答