Ef Core 接收错误
System.InvalidOperationException: Can't process set operations after client evaluation, consider moving the operation before the last Select() call (see issue #16243) at Microsoft.EntityFrameworkCore.Query.SqlExpressions.SelectExpression.ApplySetOperation(SetOperationType setOperationType, SelectExpression select2, Boolean distinct)
执行时
public async Task<object> GetUnitsForDataTableAsync() =>
await context.Units
.Where(x => !x.TractUnitJunctions.Any())
.Select(x => new
{
x.Id,
x.UnitName,
x.UnitAcres,
TractNum = String.Empty,
Wells = String.Empty,
NumOfWells = 0,
})
.Union(
context.TractUnitJunctions
.Select(x => new
{
Id = x.UnitId,
x.Unit.UnitName,
x.Unit.UnitAcres,
x.Tract.TractNum,
Wells = string.Join(", ", x.TractUnitJunctionWellJunctions
.Select(z => $"{z.Well.WellNum} ({z.Well.ApiNum})")
),
NumOfWells = x.TractUnitJunctionWellJunctions.Count()
}))
.ToListAsync().ConfigureAwait(false);
但是,如果我将它分成两个查询,该函数可以正常工作。
public async Task<object> GetUnitsForDataTableAsync()
{
var List1 = await context.Units
.Where(x => !x.TractUnitJunctions.Any())
.Select(x => new
{
x.Id,
x.UnitName,
x.UnitAcres,
TractNum = String.Empty,
Wells = String.Empty,
NumOfWells = 0,
})
.ToListAsync().ConfigureAwait(false);
var List2 = await context.TractUnitJunctions
.Select(x => new
{
Id = x.UnitId,
x.Unit.UnitName,
x.Unit.UnitAcres,
x.Tract.TractNum,
Wells = string.Join(", ", x.TractUnitJunctionWellJunctions
.Select(z => $"{z.Well.WellNum} ({z.Well.ApiNum})")
),
NumOfWells = x.TractUnitJunctionWellJunctions.Count()
})
.ToListAsync().ConfigureAwait(false);
return List1.Concat(List2);
}
我已经对该错误进行了一些研究,但我不确定如何重构第一个查询来解决该错误
最佳答案
在 .Union
之前为第一个查询添加 .AsEnumerable()
可以解决问题
如下
public async Task<object> GetUnitsForDataTableAsync() =>
await context.Units
.Where(x => !x.TractUnitJunctions.Any())
.Select(x => new
{
x.Id,
x.UnitName,
x.UnitAcres,
TractNum = String.Empty,
Wells = String.Empty,
NumOfWells = 0,
}).AsEnumerable()
.Union(
context.TractUnitJunctions
.Select(x => new
{
Id = x.UnitId,
x.Unit.UnitName,
x.Unit.UnitAcres,
x.Tract.TractNum,
Wells = string.Join(", ", x.TractUnitJunctionWellJunctions
.Select(z => $"{z.Well.WellNum} ({z.Well.ApiNum})")
),
NumOfWells = x.TractUnitJunctionWellJunctions.Count()
}))
.ToListAsync().ConfigureAwait(false);
关于c# - 客户端评估 efcore 后无法处理集合操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64647224/