0

I'm having trouble getting a specific value into the Untis_Proffield.

Code Sample:

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

Error:

System.InvalidOperationException: The LINQ expression 'DbSet<Teacher>()
.Where(t => __progress_EnteringTeacherName_0 == string.Format(
format: "{0} {1}",
arg0: t.LastName,
arg1: t.FirstName))'
could not be translated. Additional information: Translation of method 'string.Format' failed. If this method can be mapped to your custom function, see https://go.microsoft.com/fwlink/?linkid=2132413 for more information. Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to 'AsEnumerable', 'AsAsyncEnumerable', 'ToList', or 'ToListAsync'. See https://go.microsoft.com/fwlink/?linkid=2101038 for more information.
at
Microsoft.EntityFrameworkCore.Query.QueryableMethodTranslatingExpressionVisitor.g__CheckTranslated|15_0(ShapedQueryExpression translated, <>c__DisplayClass15_0& )
at
Microsoft.EntityFrameworkCore.Query.QueryableMethodTranslatingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCallExpression)

Can someone help me?

Rufus L
  • 36,127
  • 5
  • 30
  • 43
Wilson Silva
  • 1,324
  • 1
  • 14
  • 25
  • 1
    The error message you've shown doesn't match the code sample (there is no `string.Format` in the code sample) – Rufus L Nov 18 '20 at 15:40
  • 1
    Have you tried just creating the string without calling another method to do so? Perhaps if you did something like: `$"{c.LastName} {c.FirstName}"` (or `c.LastName + " " + c.FirstName`) – Rufus L Nov 18 '20 at 15:41
  • Does this answer your question? [LINQ to Entities does not recognize the method 'System.String Format(System.String, System.Object, System.Object)'](https://stackoverflow.com/questions/10079990/linq-to-entities-does-not-recognize-the-method-system-string-formatsystem-stri) – d219 Nov 18 '20 at 15:54

1 Answers1

2

Does this not work for you?

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, does not understand how to turn string.Join to a database query. You will either have to work around this, or get all the teachers in memory this._dbContext.Teachers.AsEnumerable and then query on the enumerable by using c# code.

By the way, using .Result is not a good practice, it's better to use the non async FirstOrDefault function if you can't use await. You are in danger of getting a deadlock.

d219
  • 2,707
  • 5
  • 31
  • 36
Athanasios Kataras
  • 25,191
  • 4
  • 32
  • 61