Linq查询过去7天的日期的不同值,运行查询时抛出异常

时间:2012-12-22 08:49:33

标签: c# .net linq entity-framework

我有一个表Employee,我通过以下方式检索了Id和Name字段:

var users = context.Employees.ToList()
                   .Select(employee => new KeyValuePair<int, string>(employee.Id,employee.Name)); 

那部分工作正常,我的问题是还有另一个表考勤设置了外键并且有一个字段LoginDate是一个DateTime值。用户可以多次登录,因此我希望获得用户在过去7天内登录的次数的不同值。

foreach (var user in users)
{
    var days = context.Attendances.Where(x => x.Id == user.Key && x.LoginDate.Date > DateTime.Now.AddDays(-7)).Distinct().ToList();
     int count = days.Count();
     _attendanceTable.Rows.Add(user.Key, user.Value, count);
 }

我正在运行出勤表的查询时出现异常:

  

LINQ to Entities不支持指定的类型成员“Date”。   仅初始化程序,实体成员和实体导航属性   得到支持。

2 个答案:

答案 0 :(得分:5)

您可以在单个查询中执行所有操作:

var date = DateTime.Now.AddDays(-7).Date; // I think you need date only here
var query = from e in context.Employees
            join a in context.Attendances on e.Id equals a.Id into g
            select new
            {
                e.Id,
                e.Name,
                Count = g.Where(x => x.LoginDate > date)
                         .GroupBy(x = > new {
                               x.LoginDate.Year,
                               x.LoginDate.Month,
                               x.LoginDate.Day 
                          }).Count()
            };

foreach(var user in query)
   _attendanceTable.Rows.Add(user.Id, user.Name, user.Count);

EntityFramework也不支持DateTime的Date属性。您应该使用匿名对象按日期部分对考勤进行分组。

生成的SQL查询将如下所示:

SELECT [Extent1].[Id] AS [Id], 
       [Extent1].[Name] AS [Name], 
    (SELECT 
        COUNT(1) AS [A1]
        FROM ( SELECT DISTINCT 
            DATEPART (year, [Extent2].[LoginDate]) AS [C1], 
            DATEPART (month, [Extent2].[LoginDate]) AS [C2],
            DATEPART (day, [Extent2].[LoginDate]) AS [C2],
            FROM [dbo].[Attendances] AS [Extent2]
            WHERE [Extent1].[Id] = [Extent2].[Id]
        )  AS [Distinct1]) AS [C1]
FROM [dbo].[Employees] AS [Extent1]

答案 1 :(得分:2)

您可以在代码中执行的某些操作不会(至少不是干净地)转换为SQL,您需要移动某些操作以便它们更好地转换。

//Figure out the day you want in advance
var sevenDaysAgo = DateTime.Now.Date.AddDays(-7);
var results = users.Select(user => new {
     user.Key,
     user.Value,
     Count = users.Join(context.Attendances, 
                        user => user.Key,
                        attendance => attendance.EmployeeId,
                        (user, attendance) => attendance.LoginDate)
                  .Where(date => date > sevenDaysAgo)
                  .Select(date => date.Day)
                  .Distinct()
                  .Count()
});

foreach (var result in results)
{        
    _attendanceTable.Rows.Add(result.Key, result.Value, result.Count);
}