首页 > 解决方案 > 查询 (LINQ) 表达式无法翻译实体框架核心

问题描述

我正在使用 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)(具有 {Id,CreatedDate 和其他字段}等属性的列表)是否是 ListOfGroupIds 的一部分,据此我需要获取行。但我得到运行时异常

查询 (LINQ) 表达式无法转换为实体框架核心,要么以可翻译的形式重写查询,要么通过插入对 AsEnumerable()、AsAsyncEnumerable()、ToList() 的调用显式切换到客户端评估,或 ToListAsync()。有关详细信息,请参阅https://go.microsoft.com/fwlink/?linkid=2101038

我检查了与此相关的不同帖子,甚至尝试在此处输入链接描述

我只有一个可行的解决方案是将 AsEnumerable 添加到查询中。但我不希望它是 AsEnumerable 因为我正在处理大量数据,并且我无法拆分包含查询,因为我需要检查一个条件( i.SentDate) 在那个 ANY 里面。

因此,如果有任何方法可以在单个查询中执行此操作而无需创建AsEnumerable

标签: c#entity-frameworkentity-framework-corelinq-to-entitiesentity-framework-core-3.1

解决方案


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

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

推荐阅读