无法翻译查询 (LINQ) 表达式 Entity Framework 核心

The Query (LINQ) expression could not be Translated Entity Framework Core

我正在使用 EntityFrameworkCore 3.1.11 并有以下查询

 var list = _context.Table1
                  .Include(i => i.ListofGroupIds)
                  .Where(i => 
                          i.ListofGroupIds.Select(x => x.GroupId).Any(m =>
                          SelectedIds.Where(z => z.CreatedDate <= i.SentDate).Select(y => y.Id).Contains(m)
                       ))
                   );

这里我需要检查 SelectedIds(具有 {Id、CreatedDate 和其他字段} 等属性的列表)中存在的任何项目 (Id) 是否是 ListOfGroupIds 的一部分,据此我需要获取行.但是我收到 运行 时间异常,因为

The Query (LINQ) expression could not be Translated Entity Framework Core,Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to either AsEnumerable(), AsAsyncEnumerable(), ToList(), or ToListAsync(). See https://go.microsoft.com/fwlink/?linkid=2101038 for more information.

我检查了与此相关的不同 post,甚至尝试了 enter link description here

我只有一个有效的解决方案是将 AsEnumerable 添加到 query.But 我不希望它成为 AsEnumerable 因为我正在处理大量数据,而且我无法拆分包含查询,因为我需要检查其中任何一个条件(i.SentDate)。

因此,如果有任何方法可以在不使 AsEnumerable.

的情况下在单个查询中执行此操作

假设这是你的结构(我故意忽略了你可能有的所有外键,这只是一个例子!)

public class Table1
{
    public int Id { get; set; }

    public virtual ListofGroupIds ListofGroupIds { get; set; }
}

public class ListofGroupIds
{
    public int GroupId { get; set; }
    public DateTime SentDate { get; set; }
}

public class SelectedIds
{
    public int Id { get; set; }
    public DateTime CreatedDate { get; set; }
}

public class MyContext : DbContext
{
    public DbSet<Table1> Table1 { get; set; }
    public DbSet<ListofGroupIds> ListofGroupIds { get; set; }
    public DbSet<SelectedIds> SelectedIds { get; set; }
}

您可以将查询重写为

var query = from tab1 in _context.Table1
                    join logi in _context.ListofGroupIds on tab1.Id equals logi.GroupId
                    join sids in _context.SelectedIds on logi.GroupId equals sids.Id
                    where sids.CreatedDate <= logi.SentDate
                    select new { tab1.Id, logi.GroupId, sids.CreatedDate }; //You can select any other columns within the tables joined

或者,如果可能,只需连接所需的两个表

var query2 = from logi in _context.ListofGroupIds
                     join sids in _context.SelectedIds on logi.GroupId equals sids.Id
                     where sids.CreatedDate <= logi.SentDate
                     select new { logi.GroupId, logi.SentDate, sids.Id, sids.CreatedDate };

或者

var query3 = _context
            .ListofGroupIds.Join(_context.SelectedIds, logi => logi.GroupId, sids => sids.Id, (logi, sids) => new { logi.GroupId, logi.SentDate, sids.Id, sids.CreatedDate })
            .Where(result => result.CreatedDate <= result.SentDate);