【问题标题】:The LINQ expression could not be translated in foreach无法在 foreach 中翻译 LINQ 表达式
【发布时间】:2021-03-01 21:47:48
【问题描述】:

我无法将特定值输入Untis_Proffield。

代码示例:

foreach (EnseignantReport test in grades)
{
    test.Untis_Prof = this._dbContext.Teachers.FirstOrDefaultAsync(c => 
        test.Untis_Prof == string.Join(" ", new[] {c.LastName, c.FirstName }))
        .Result.UntisCode;
}

错误:

System.InvalidOperationException:LINQ 表达式'DbSet<Teacher>()
.Where(t => __progress_EnteringTeacherName_0 == string.Format(
format: "{0} {1}",
arg0: t.LastName,
arg1: t.FirstName))'
无法翻译。附加信息:方法'string.Format' 的翻译失败。如果此方法可以映射到您的自定义函数,请参阅https://go.microsoft.com/fwlink/?linkid=2132413 了解更多信息。以可翻译的形式重写查询,或通过插入对“AsEnumerable”、“AsAsyncEnumerable”、“ToList”或“ToListAsync”的调用显式切换到客户端评估。请参阅https://go.microsoft.com/fwlink/?linkid=2101038 了解更多信息。

Microsoft.EntityFrameworkCore.Query.QueryableMethodTranslatingExpressionVisitor.g__CheckTranslated|15_0(ShapedQueryExpression 已翻译,c__DisplayClass15_0& )

Microsoft.EntityFrameworkCore.Query.QueryableMethodTranslatingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCallExpression)

有人可以帮我吗?

【问题讨论】:

标签: c# asp.net .net entity-framework


【解决方案1】:

这不适合你吗?

foreach (EnseignantReport test in grades)
{
    test.Untis_Prof = this._dbContext.Teachers.FirstOrDefaultAsync(c => 
        test.Untis_Prof == c.LastName + " " + c.FirstName }))
        .Result.UntisCode;
}

Linq to DB,不明白如何转换字符串。加入数据库查询。你要么必须解决这个问题,要么让所有教师在内存中 this._dbContext.Teachers.AsEnumerable,然后使用 c# 代码查询可枚举。

顺便说一句,使用.Result不是一个好习惯,如果你不能使用await,最好使用非异步的FirstOrDefault函数。你有陷入僵局的危险。

【讨论】:

    猜你喜欢
    • 2021-12-28
    • 1970-01-01
    • 2022-12-03
    • 2021-11-26
    • 1970-01-01
    • 2021-11-27
    • 2022-10-20
    • 1970-01-01
    相关资源
    最近更新 更多