无法翻译 LINQ 表达式。通过插入对 'AsEnumerable'、'AsAsyncEnumerable'、'ToList' 的调用来显式进行客户评估

LINQ expression could not be translated. client evaluation explicitly by inserting a call to 'AsEnumerable', 'AsAsyncEnumerable', 'ToList'

错误信息

The LINQ expression 'DbSet<Project>()
    .Join(
        inner: __p_0, 
        outerKeySelector: p => p.ProjectId, 
        innerKeySelector: t => t.ProjectId, 
        resultSelector: (p, t) => new ProjectDateModel{ 
            ProjectId = p.ProjectId, 
            ProjectName = p.ProjectName, 
            Date = t.Date 
        }
    )' could not be translated. Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to 'AsEnumerable', 'AsAsyncEnumerable', 'ToList', or 'ToListAsync'. See https://go.microsoft.com/fwlink/?linkid=2101038 for more information.

这是我的 ef 模型

public partial class Task
    {
        public int TaskId { get; set; }
        public int EmployeeId { get; set; }
        public int ProjectId { get; set; }
        public DateTime? Date { get; set; }
    }
public partial class Project
    {
        public int ProjectId { get; set; }
        public string ProjectName { get; set; }
    }

我想在这里实现的是,select特定月份的所有任务 select task.ProjectId 和 project.ProjectId 的所有项目 我的 linq 表达式

var date = new DateTime(year, month, 1);
        var projectModel = new List<ProjectDateModel>();
        for (int i = 0; i < DateTime.DaysInMonth(year, month); i++)
        {
          var tasks = _context.Task.Where(t => t.Date == date && a.EmployeeId == employeeId).ToList();
          var projects = _context.Project.Join(tasks, p => p.ProjectId, t => t.ProjectId, (p, t) => new ProjectDateModel {
            ProjectId = p.ProjectId,
            ProjectName = p.ProjectName,
            Date = a.Date
          }).ToList();
          projectModel.AddRange(projects);
          date = date.AddDays(1);
        }

        return (projectModel);

项目日期模型

public class ProjectDateModel
    {
        public int ProjectId { get; set; }
        public string ProjectName { get; set; }
        public DateTime? Date { get; set; }
    }

问题可能是您执行了一个 EF 查询并调用了 ToList,然后尝试将该本地列表与另一个 EF 查询加入。

这都是 LINQ,但您混合了两个不同的提供程序:

  • LINQ to Objects 和
  • LINQ to Entities。

您的 EF 查询需要能够转换为 SQL 代码才能在数据库上执行,但数据库中不存在您的本地列表。摆脱对第一个查询的 ToList 调用,我怀疑它会起作用。

试试那种方式,我只是不确定日期属性

var tasks = _context.Tasks
    .Where(x => SqlFunctions.DatePart("month", x.Date) == date.Month && x.EmployeeId == employeeId)
    .ToList();

var taskIds = tasks.Select(x => x.ProjectId);

var projects = _context.Projects
    .Where(x => taskIds.Contains(x.ProjectId))
    .Select(x => new ProjectDateModel
          {
               ProjectId = x.ProjectId,
               ProjectName = x.ProjectName,
               Date = tasks.FirstOrDefault(y => y.ProjectId == x.ProjectId).Date,
          });