c# - 查询 (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。
解决方案
假设这是您拥有的结构(我忽略了您可能故意拥有的所有外键,这只是一个示例!)
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);
推荐阅读
- javascript - 为什么 json 文件中的 document.createElement('br') 不可见
- html - Magick CSS 以不同方式应用于字符串的每个字符
- python - 折叠多维 NumPy 数组的简单方法
- nginx - 可恢复的js正在触发fileSuccess,而块没有在服务器中组装
- github-actions - GitHub Actions - 不止一个 cron
- r - 如何在动画地图 R 上添加第二个点变量?
- html - 如何使用 HTML 通过按钮重新创建表格?
- reactjs - reactjs中如何调用另一个文件的函数
- python - 设置 s3 子目录路径并使用 boto 删除它的 Python 方法
- wordpress - 将CF7扩展插件“Images Optimize and Upload CF7”图像数据保存到CPT的ACF图像字段中