0

im actually dont know how i should fix my following problem. Before i show you my code, i will explain the situation. So there comes a list of strings from my frontend, which needs to be compared with items of my database. The goal is to filter with my frontend list, so there are only results on my Website with the selected elements. I created already multiple expressions but none of these could be translated.

Here is the problem:

.Where(p => user.personenTypFilter.Any(i => 
    p.Personentypzuordnungens.ToList().Any(u => u.Personentyp.Bezeichnung == i)))

So personenTypFilter is my List from my Frontend. Personentypzuordnungens is a table of my Database which collect the strings of the persontyp through a Foreign key(u.personentyp.bezeichnung). My Idea is going through the personenTypFilter with Any and compare with another Any in the Database.

I get no results and only a translation error:

"System.InvalidOperationException: The LINQ expression 'DbSet<Personen>()
    .Where(p => p.Vorname.ToLower().Contains(__user_vorname_0))
    .Where(p => p.Nachname.ToLower().Contains(__user_nachname_1))
    .Where(p => p.Anrede.ToLower().Contains(__user_anrede_2))
    .Where(p => p.Ort.ToLower().Contains(__user_adresse_3) || p.Plz.Contains(__user_adresse_3) || p.Land.Contains(__user_adresse_3) || p.Bundesland.Contains(__user_adresse_3) || p.Straße.Contains(__user_adresse_3))
    .Where(p => p.Firmenbezeichnung.ToLower().Contains(__user_firmenbezeichnung_4))
    .Where(p => __user_personenTypFilter_5
        .Any(i => DbSet<Personentypzuordnungen>()
            .Where(p0 => EF.Property<Nullable<Guid>>(p, "PersonId") != null && object.Equals(
                objA: (object)EF.Property<Nullable<Guid>>(p, "PersonId"), 
                objB: (object)EF.Property<Nullable<Guid>>(p0, "PersonId")))
            .Join(
                inner: DbSet<Personentypen>(), 
                outerKeySelector: p0 => EF.Property<Nullable<Guid>>(p0, "PersonentypId"), 
                innerKeySelector: p1 => EF.Property<Nullable<Guid>>(p1, "PersonentypId"), 
                resultSelector: (o, i) => new TransparentIdentifier<Personentypzuordnungen, Personentypen>(
                    Outer = o, 
                    Inner = i
                ))
            .Any(p0 => p0.Inner.Bezeichnung == i)))' could not be translated. 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.<VisitMethodCall>g__CheckTranslated|15_0(ShapedQueryExpression translated, <>c__DisplayClass15_0& )
   at Microsoft.EntityFrameworkCore.Query.QueryableMethodTranslatingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCallExpression)
   at Microsoft.EntityFrameworkCore.Query.QueryableMethodTranslatingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCallExpression)
   at Microsoft.EntityFrameworkCore.Query.QueryableMethodTranslatingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCallExpression)
   at Microsoft.EntityFrameworkCore.Query.QueryableMethodTranslatingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCallExpression)
   at Microsoft.EntityFrameworkCore.Query.QueryableMethodTranslatingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCallExpression)
   at Microsoft.EntityFrameworkCore.Query.QueryableMethodTranslatingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCallExpression)
   at Microsoft.EntityFrameworkCore.Query.QueryableMethodTranslatingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCallExpression)
   at Microsoft.EntityFrameworkCore.Query.QueryableMethodTranslatingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCallExpression)
   at Microsoft.EntityFrameworkCore.Query.QueryCompilationContext.CreateQueryExecutor[TResult](Expression query)
   at Microsoft.EntityFrameworkCore.Storage.Database.CompileQuery[TResult](Expression query, Boolean async)
   at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.CompileQueryCore[TResult](IDatabase database, Expression query, IModel model, Boolean async)
   at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.<>c__DisplayClass12_0`1.<ExecuteAsync>b__0()
   at Microsoft.EntityFrameworkCore.Query.Internal.CompiledQueryCache.GetOrAddQuery[TResult](Object cacheKey, Func`1 compiler)
   at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.ExecuteAsync[TResult](Expression query, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryProvider.ExecuteAsync[TResult](Expression expression, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryable`1.GetAsyncEnumerator(CancellationToken cancellationToken)
   at System.Runtime.CompilerServices.ConfiguredCancelableAsyncEnumerable`1.GetAsyncEnumerator()
   at Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.ToListAsync[TSource](IQueryable`1 source, CancellationToken cancellationToken)
   at DadaAPI.Controllers.PersonensController.Filter(Filter user) in C:\Users\Dada\source\repos\DadaAPI\DadaAPI\Controllers\Personen\PersonensController.cs:line 125
   at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.TaskOfIActionResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeActionMethodAsync>g__Awaited|12_0(ControllerActionInvoker invoker, ValueTask`1 actionResultValueTask)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeNextActionFilterAsync>g__Awaited|10_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeInnerFilterAsync()
--- End of stack trace from previous location ---
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResourceFilter>g__Awaited|24_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed context)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeFilterPipelineAsync()
--- End of stack trace from previous location ---
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
   at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
   at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
   at Swashbuckle.AspNetCore.SwaggerUI.SwaggerUIMiddleware.Invoke(HttpContext httpContext)
   at Swashbuckle.AspNetCore.Swagger.SwaggerMiddleware.Invoke(HttpContext httpContext, ISwaggerProvider swaggerProvider)
   at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

HEADERS
=======
Cache-Control: no-cache
Connection: keep-alive
Pragma: no-cache
Content-Type: application/json
Accept: application/json, text/plain, */*
Accept-Encoding: gzip, deflate, br
Accept-Language: de-DE,de;q=0.9,en-US;q=0.8,en;q=0.7
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJhM2YzZDA3NS0xODQ1LTQwNzEtYTU4ZS1mMGM5Yzc4MTJhNTAifQ.NaPhXxgCCy7r9mUFZ54DC4DIMwe21GNnO3-8GFdtPWQ
Host: localhost:5000
Referer: http://localhost:4200/
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.69 Safari/537.36
Origin: http://localhost:4200
Content-Length: 576
sec-ch-ua: "Google Chrome";v="95", "Chromium";v="95", ";Not A Brand";v="99"
sec-ch-ua-mobile: ?0
sec-ch-ua-platform: "Windows"
Sec-Fetch-Site: same-site
Sec-Fetch-Mode: cors
Sec-Fetch-Dest: empty
"

Full Query:

public async Task<IActionResult> Filter([FromBody] Filter user)
{
    //Variable für Personentypen als Liste machen
    return Ok(await _context
        .Personens
        //Obere Felder (nicht erweitert)
        .Where(p => p.Vorname.ToLower().Contains(user.vorname))
        .Where(p => p.Nachname.ToLower().Contains(user.nachname))
        .Where(p => p.Anrede.ToLower().Contains(user.anrede))
        .Where(p => p.Ort.ToLower().Contains(user.adresse) || p.Plz.Contains(user.adresse) || p.Land.Contains(user.adresse) || p.Bundesland.Contains(user.adresse) || p.Straße.Contains(user.adresse))
        .Where(p => p.Firmenbezeichnung.ToLower().Contains(user.firmenbezeichnung))
        .Where(p => user.personenTypFilter.Any(i => p.Personentypzuordnungens.ToList().Any(u => u.Personentyp.Bezeichnung == i)))
        .Where(p => p.ArbeitgeberPersonIdTNavigation.Ort.ToLower().Contains(user.arbeitgeberOrt) || p.ArbeitgeberPersonIdTNavigation.Plz.ToLower().Contains(user.arbeitgeberOrt)
                    || p.ArbeitgeberPersonIdTNavigation.Straße.ToLower().Contains(user.arbeitgeberOrt) || p.ArbeitgeberPersonIdTNavigation.Land.ToLower().Contains(user.arbeitgeberOrt) || p.ArbeitgeberPersonIdTNavigation.Bundesland.ToLower().Contains(user.arbeitgeberOrt))
        .Select(p => new
        {
            personId = p.PersonId,
            nachname = p.Nachname,
            vorname = p.Vorname,
            plz = p.Plz,
            firmBez = p.Firmenbezeichnung,
            ort = p.Ort,
            personentyp = p.Personentypzuordnungens.Select(i => new
            {
                personentypId = i.PersonentypId,
            }),
            aktuellePosition = p.AktuellePosition,
            taetigkeit = p.Tätigkeit,
            kernkompetenzen = p.Kernkompetenzen,
            datenReviewedZeitpunkt = p.DatenReviewedZeitpunkt,
        }).ToListAsync());
}
Svyatoslav Danyliv
  • 21,911
  • 3
  • 16
  • 32
Chopper
  • 47
  • 1
  • 9
  • Remove `ToList` from `Where`. – Svyatoslav Danyliv Nov 17 '21 at 09:39
  • Same Error like before – Chopper Nov 17 '21 at 09:43
  • 1
    Try the following: `.Where(p => user.personenTypFilter.SelectMany(u => p.Personentypzuordnungens).Any(u => u.Personentyp.Bezeichnung == i))` – Svyatoslav Danyliv Nov 17 '21 at 10:04
  • Show full query. Not a part. – Svyatoslav Danyliv Nov 17 '21 at 10:05
  • I fixed your code to .Where(p => user.personenTypFilter.SelectMany(i => p.Personentypzuordnungens).Any(u => u.Personentyp.Bezeichnung == i)), after that i cant reaach i anymore because of SelectMany. I will edit my post above, but it will not change the situation. Other stuff is working – Chopper Nov 17 '21 at 10:09
  • 1
    Well, `user.personenTypFilter` is local collection. Such complex `Any` is not supported with local collections. Use [FilterByItems](https://stackoverflow.com/a/67666993/10646316) and it will generate needed predicate. And for sure remove `ToList` from `Where` body. – Svyatoslav Danyliv Nov 17 '21 at 10:30
  • Okay i implemented the function and i dont get any translation erros anymore, thx for that! My new problem is that i dont get any results back, my line looks like: .FilterByItems(user.personenTypFilter, (m,k) => m.Personentypzuordnungens.Any(x => x.Personentyp.Bezeichnung.Contains(k)),true), it seems that the any is my problem, i tried it also with select but that throws errors – Chopper Nov 17 '21 at 10:53
  • Got it now also with Select done, still no results – Chopper Nov 17 '21 at 10:59
  • 1
    Analyze generated SQL, and identify why records are omitted . Here i cannot help. personenTypFilter has items? – Svyatoslav Danyliv Nov 17 '21 at 11:09
  • Yes, mhm kk. Ty for your help! I think the last steps i need to go alone :D – Chopper Nov 17 '21 at 11:18

0 Answers0