具有 Contains 和可为 Null 值的 Linq 查询
我有一个搜索方法,如下所示:
public IEnumerable<Result> Search(string searchText)
{
return _context.Person.Where(x => x.Contains(searchText));
}
我希望能够在 searchText
为空/空的情况下调用此函数并取回所有记录。
我尝试过这个,但没有成功:
return _context.Person.Where(x => x.Contains(searchText ?? ""));
除了将其分为两个步骤并在将其应用于查询之前在 if 语句中检查 searchString
之外,还有其他方法可以实现此目的吗?
I have a method for searching which looks like this:
public IEnumerable<Result> Search(string searchText)
{
return _context.Person.Where(x => x.Contains(searchText));
}
I want to be able to call this function with searchText
being null/empty and get all of the records back.
I have tried this with no luck:
return _context.Person.Where(x => x.Contains(searchText ?? ""));
is there another way to accomplish this besides breaking it up into two steps and checking searchString
in an if statement before applying it to the query?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
你可以这样做:
这是一个我经常使用的模式,当我有参数时,我只想在设置它们时应用它们。
You can do it like this:
This is a pattern I use a lot when I have parameters I want to apply only if they are set.
还有一种效率较低的方法...不确定这在语义上是否正确,但你明白了...
And a less efficient way... Not sure if this is semantically correct but you get the idea...
或者
or
假设
Person
是一个类Contains
似乎是该类的方法。类似Where(x => x.Contains(searchText))
或Where(x => string.IsNullOrEmpty(searchText) || x.Contains(searchText))
的表达式code> where x is a Person 根本无法与 LINQ to Entities 一起使用,即使是像 ...... 这样的简单类,它也会抛出异常,因为 LINQ to Entities 无法将此方法转换为存储表达式。
Where(x => string.IsNullOrEmpty(searchText) || x.Name.Contains(searchText))
可以工作。Assuming that
Person
is a classContains
seems to be method of this class. An expression likeWhere(x => x.Contains(searchText))
orWhere(x => string.IsNullOrEmpty(searchText) || x.Contains(searchText))
where x is a Person won't work at all with LINQ to Entities, even with a simple class like ...... it will throw an exception because LINQ to Entities can't translate this method to a storage expression.
Where(x => string.IsNullOrEmpty(searchText) || x.Name.Contains(searchText))
would work though.我尝试了所有解决方案,下面的解决方案对我有用
问题
I try all solutions and just below solution worked for me
Issues