如何在LINQ中编写以下查询

时间:2013-05-03 10:05:31

标签: c# linq linq-to-sql linq-to-entities

我有一个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) 

这将返回如下结果

enter image description here

我尝试了什么

 //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"));     

我的结果总体上是Count(例如,如果我从4月1日到4月15日选择,结果是所有“完成”的总和),但我需要计算每一天在此选中范围。结果我将绑定到柱形图。 如何进行 ?

3 个答案:

答案 0 :(得分: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

答案 1 :(得分: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()});

答案 2 :(得分: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();