我有一个搜索代码,它使用三个参数进行搜索,但我希望传递一个参数并将其与代码中的所有三个或四个或任意数量的变量相匹配。任何人都可以向我展示前进的方向
ICriteria oCriteria = base.Session.CreateCriteria<Patient>("p").CreateCriteria("User", "u", NHibernate.SqlCommand.JoinType.InnerJoin)
.Add(Restrictions.Eq("u.IsDeleted", false)).Add(Restrictions.Eq("u.IsPatientSignUp", false)).Add(Restrictions.Like("u.FirstName", '%' + data + "%"))
.Add(Restrictions.Like("u.LastName", '%' + data + "%")).Add(Restrictions.Like("u.Email", '%' + data + "%"))
.Add(Restrictions.Or(cr1, cr2))
.AddOrder(Order.Asc(Projections.Cast(NHibernateUtil.Int32, Projections.Property("p.MedNexusId"))));
patient = oCriteria.List<Patient>().Skip(pageNumber * pageSize).Take(pageSize).ToList();
答案 0 :(得分:2)
NHibernate为我们提供了一套基本工具(本例中的限制),我们可以扩展它们(创建新的ICriterion
)或将它们组合起来。所以我们可以创建这样的常用方法:
// multiple AND
public static AbstractCriterion AllLike(IEnumerable<string> properties, string toCompare)
{
Conjunction conjunction = Restrictions.Conjunction();
foreach (var name in properties)
{
conjunction.Add(Restrictions.Like(name, toCompare, MatchMode.Anywhere));
}
return conjunction;
}
// multiple OR
public static AbstractCriterion AnyLike(IEnumerable<string> properties, string toCompare)
{
Disjunction disjunction = Restrictions.Disjunction();
foreach (var name in properties)
{
disjunction.Add(Restrictions.Like(name, toCompare, MatchMode.Anywhere));
}
return disjunction;
}
现在我们可以称之为:
ICriteria oCriteria = ....
var toMatch = new[] {"u.LastName", "u.Email", ...};
criteria.Add(AllLike(toMatch, data));
// or
criteria.Add(AnyLike(toMatch, data));
注意:类似的实现已经存在Restrictions.AllEq(IDictionary propertyNameValues)