Reputation: 141
I have a search code which searches using three parameters but i want to pass a single parameter and match it with all three or four or any number of variables in the code.Can any one show me the way forward
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();
Upvotes: 2
Views: 143
Reputation: 123861
NHibernate gives us a set of basic tools (Restrictions in this case) and we can either extend them (create new ICriterion
) or combine them. So we can create common methods like these:
// 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;
}
And now we can call them like:
ICriteria oCriteria = ....
var toMatch = new[] {"u.LastName", "u.Email", ...};
criteria.Add(AllLike(toMatch, data));
// or
criteria.Add(AnyLike(toMatch, data));
NOTE: the similar implementation is already there Restrictions.AllEq(IDictionary propertyNameValues)
Upvotes: 2