我的查询表达式执行时工作正常。
var topQuery1 = (
from rov in context.Rocks
.Where(x => eIds.Contains(x.RockId))
join ro in context.Rocks
.Where(x => x.Break == "OUT")
.OrderByDescending(x => x.Timestamp)
on
new { rov.WorkerId, rov.Flatter } equals
new { ro.WorkerId, ro.Flatter }
into _rovOut
from rovOut in _rovOut.DefaultIfEmpty()
join ao in context.Workers()
on rov.WorkerId equals ao.WorkerId
into _profile
from profile in _profile.DefaultIfEmpty()
select new { rov, rovOut, profile }
);
我将上面的代码翻译成这个 FluentAPI,但没有按预期工作。
var topQuery2 = context.Rocks.Where(x => eIds.Contains(x.RockId))
.GroupJoin(context.Workers(),
r => r.WorkerId,
p => p.WorkerId,
(a, b) => new { profile = b.SingleOrDefault(), rov = a })
.GroupJoin(context.Rocks.Where(x => x.Break == "OUT").OrderByDescending(x => x.Timestamp),
a => new { a.rov.WorkerId, a.rov.Flatter },
b => new { b.WorkerId, b.Flatter },
(a, b) => new { rovOut = b.SingleOrDefault(), rov = a.rov, profile = a.profile });
它产生错误:
创建查询字符串时出错:LINQ 表达式 'DbSet() .Where(x => __eIds_0 .包含(x.RockId)) .GroupJoin( 内部:DbSet(), 外键选择器:r => r.WorkerId, 内部KeySelector:p => p.WorkerId, 结果选择器:(a,b)=>新{ 配置文件 = b.SingleOrDefault(), 罗夫 = a })' 无法翻译。要么以可翻译的形式重写查询,要么显式切换到客户端评估 通过插入对 'AsEnumerable'、'AsAsyncEnumerable'、'ToList' 的调用, 或“ToListAsync”。请参阅https://go.microsoft.com/fwlink/?linkid=2101038 欲了解更多信息..
我认为问题出在
eIds
字段,你在哪里以及如何计算它? (如果你发布它,我会审查这个答案)
linq 中列表和包含的常见问题是这样的:
var eIds =
myContext.SomeTable
.Select(x=>x.id)
var otherQuery =
myContext.SomeTable2
.Where(x=>eIds.contains(x.Id2))
.ToList()
这会在 Linq to SQL 中引发错误,因为在第二个查询中 ids 无法转换为 SQL。在使用
.ToList()
字段之前使用
eIds
进行解析,如下所示:
var eIds =
myContext.SomeTable
.Select(x=>x.id)
.ToList()
var otherQuery =
myContext.SomeTable2
.Where(x=>eIds.contains(x.Id2))
.ToList()