nhibernate queryover LIKE与表达式树 [英] nhibernate queryover LIKE with expression trees
问题描述
我想在我的基本存储库类中添加一个方法,允许我使用 LIKE 表达式,但是我不太确定该怎么做.我想创建一个通用方法,该方法查看传入的表达式树,并在传入的字符串值中查找通配符.然后将相应地生成QueryOver
语句.
I'm looking to add a method to my base repository class that allows me to use LIKE expressions but I'm not quite sure of how to go about this. I want to create a generic method that looks at the expression tree passed in and looks for wildcard characters in the string values passed in. It would then generate the QueryOver
statement accordingly.
我目前有以下内容:
public IList<T> FindAll(Expression<Func<T, bool>> criteria, char wildCard)
{
return SessionFactory.GetCurrentSession()
.QueryOver<T>()
.Where(criteria)
.List();
}
显然,困难的部分尚未到来.我需要浏览表达式树并动态地使用QueryOver
建立查询.寻找一些有关如何进行此操作的指示.还是我只是在这里浪费时间,应该在我的存储库中创建用于处理 Like 查询的单个方法?
Obviously the hard part is yet to come. I need to look through the expression tree and build the query using QueryOver
dynamically. Looking for some pointers on how to proceed with this. Or am I just wasting my time here and should just create individual methods in my repositories that handle the LIKE queries?
理想情况下,我想告诉您以下两者之间的区别:
Ideally I'd like to tell the difference between the following:
- 搜索*
- *搜索
- *搜索*
因此生成的查询将是:
- 像搜索%"这样的字段
- 像%search"这样的字段
- 像%search%"这样的字段
推荐答案
有两种方法在QueryOver中编写Like表达式.
There's two ways to write a Like expression in QueryOver.
如果您在Where子句中这样做:
If you do it off the Where clause:
.Where(Restrictions.Like(Projections.Property<T>(*projected property*), *string value*, MatchMode.Anywhere))
但是,这有点长.
因此您可以使用WhereRestrictionOn:
So you can use WhereRestrictionOn:
.WhereRestrictionOn(*projected property*).IsLike(*string value*, MatchMode.Anywhere)
这意味着您需要传递两个参数,例如:
This means you need to pass in two parameters like:
FindAll<User>(x => x.FirstName, "bob");
您也许可以使用.Contains,.StartsWith,.EndsWith,但我不确定.
You may be able to use .Contains, .StartsWith, .EndsWith, but I'm not sure.
FindAll<User>(x => x.FirstName.Contains("bob"));
FindAll<User>(x => x.FirstName.StartsWith("bob"));
FindAll<User>(x => x.FirstName.EndsWith("bob"));
我认为这些内容在NHibernate中不起作用.
I don't think those work in NHibernate.
希望有帮助.
这篇关于nhibernate queryover LIKE与表达式树的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!