首页 > 解决方案 > StartsWith 使用 LINQ 和实体框架从列表到 SQL 请求的任何字符串

问题描述

我可以通过以下请求从 EF 获取对象:

apples = apples.Where(a => a.Sort.Name.StartsWith("Gold"))

但我想知道是否可以使用字符串列表而不是一个字符串?我已经尝试过这样做:

List<string> list = {...}

apples = apples.Where(a => list.Any(x => a.Sort.Name.StartsWith(x)))

但它给了我奇怪的错误:

System.ArgumentOutOfRangeException:指定的参数超出了有效值的范围。(参数'索引')在 System.Linq.Expressions.InstanceMethodCallExpression1.GetArgument(Int32 索引)在 Npgsql.EntityFrameworkCore.PostgreSQL.Query.ExpressionVisitors.NpgsqlSqlTranslatingExpressionVisitor.VisitLikeAnyAll(SubQueryExpression 表达式)在 Npgsql.EntityFrameworkCore.PostgreSQL.Query.ExpressionVisitors.NpgsqlSqlTranslatingExpressionVisitor .VisitSubQuery(SubQueryExpression expression) at Microsoft.EntityFrameworkCore.Query.ExpressionVisitors.SqlTranslatingExpressionVisitor.Visit(Expression expression) at Microsoft.EntityFrameworkCore.Query.ExpressionVisitors.SqlTranslatingExpressionVisitor.VisitBinary(BinaryExpression expression) at Npgsql.EntityFrameworkCore.PostgreSQL.Query.ExpressionVisitors.NpgsqlSqlTranslatingExpressionVisitor .1 bodyClauses, QueryModel queryModel) at Remotion.Linq.QueryModelVisitorBase.VisitQueryModel(QueryModel queryModel) at Microsoft.EntityFrameworkCore.Query.EntityQueryModelVisitor.VisitQueryModel(QueryModel queryModel) at Microsoft.EntityFrameworkCore.Query.RelationalQueryModelVisitor.VisitQueryModel(QueryModel queryModel) at Microsoft.EntityFrameworkCore.Query.EntityQueryModelVisitor.CreateAsyncQueryExecutor[TResult](QueryModel queryModel) at Microsoft.EntityFrameworkCore.Storage.Database.CompileAsyncQuery[TResult](QueryModel queryModel) at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.CompileAsyncQueryCore[TResult](Expression query, IQueryModelGenerator queryModelGenerator, IDatabase database) at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.<>c__DisplayClass22_01.b__0() 在 Microsoft.EntityFrameworkCore.Query.Internal.CompiledQueryCache.GetOrAddQueryCore[TFunc](Object cacheKey, Func 1 compiler) at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.ExecuteAsync[TResult](Expression query) at Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryable1.System.Collections.Generic.IAsyncEnumerable.GetEnumerator() 在 System.Linq.AsyncEnumerable.Aggregate_[TSource,TAccumulate ,TResult](IAsyncEnumerable 1 source, TAccumulate seed, Func3 accumulator, Func`2 resultSelector, CancellationToken cancelToken) in D:\a\1\s\Ix.NET\Source\System.Interactive.Async\Aggregate.cs:line 118 at {my project}

标签: c#postgresqllinqentity-framework-core

解决方案


无法得到与您相同的错误(刚刚翻译失败,因此如果您可以添加最小的可重现示例,那就太好了),因为我使用的是EF.Functions.ILike(使用最新的 npgsql 包):

List<string> list = new() {"a%", "b%"};
var result = ctx.Apples
    .Where(c => list.Any(xx => EF.Functions.ILike(c.Sort.Name, xx)))
    .ToList();

据我所知,目前StartsWith还没有实现对使用本地集合的支持(基于这个 PR这个评论),只有EF.Functions.LikeEF.Functions.ILike


推荐阅读