我的实体是:
Public class Sample
{
public int Id { get; set; }
public string Caption { get; set; }
}
串词列表为:
List<string> words;
我正在使用这段代码来达到结果:
var query = _sampleRepository.AsQueryable().AsNoTracking(); // the type is IQueryable<Sample>
query = query.Where(x => words.Any(word => x.Caption.Contains(word)));
query = query.OrderByDescending(x => x.Id).Skip(50).Take(20);
query = query.ToList();
但是在执行上面的代码时,我会得到一个 Exception,它说: 的代码部分
query.Where(x => words.Any(word => x.Caption.Contains(word))) 可以 不会被 EF 翻译成这样的查询以从数据库中获取数据!我实际上想要并且我应该使用 LINQ 来执行此操作并且不可能使用例如
connection.QuerySingleOrDefaultAsync
方法等请帮我做到这一点!
var query = _sampleRepository.AsQueryable().AsNoTracking(); // the type is IQueryable<Sample>
Expression<Func<Sample, bool>> predicate = (Sample) => false;
foreach(var word in words)
predicate = predicate.Or(x => x.Caption.Contains(word));
query= query.Where(predicate);
query = query.OrderByDescending(x => x.Id).Skip(50).Take(20);
query = query.ToList();
我应该使用
LinqKit
的
Nuget Package来帮助我做到这一点! 这是解决方案代码:
var pb = PredicateBuilder.New<Sample>();
foreach (var word in words)
{
pb = pb.Or(x => x.Caption.Contains(word));
}
query = query.Where(pb);
我需要 LinqKit 来使用 PredicateBuilder,上面的代码应该替换为 query = query.Where(x => words.Any(word => x.Caption.Contains(word)));
,它对我有用!