3

我有一个 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 不支持指定的类型成员“日期”。仅支持初始化程序、实体成员和实体导航属性。

4

2 回答 2

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

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

生成的 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]
于 2012-12-22T09:06:08.940 回答
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);
}
于 2012-12-22T08:54:41.690 回答