How to do a proper search with nhibernate
Posted
by Denis Rosca
on Stack Overflow
See other posts from Stack Overflow
or by Denis Rosca
Published on 2010-05-27T16:57:43Z
Indexed on
2010/05/31
21:43 UTC
Read the original article
Hit count: 259
Hello everyone,
i'm working on a small project that is supposed to allow basic searches of the database. Currently i'm using nhibernate for the database interaction. In the database i have 2 tables: Person and Address. The Person table has a many-to-one relationship with Address.
The code i've come up with for doing searches is:
public IList<T> GetByParameterList(List<QueryParameter> parameterList)
{
if (parameterList == null)
{
return GetAll();
}
using (ISession session = NHibernateHelper.OpenSession())
{
ICriteria criteria = session.CreateCriteria<T>();
foreach (QueryParameter param in parameterList)
{
switch (param.Constraint)
{
case ConstraintType.Less:
criteria.Add(Expression.Lt(param.ParameterName, param.ParameterValue));
break;
case ConstraintType.More:
criteria.Add(Expression.Gt(param.ParameterName, param.ParameterValue));
break;
case ConstraintType.LessOrEqual:
criteria.Add(Expression.Le(param.ParameterName, param.ParameterValue));
break;
case ConstraintType.EqualOrMore:
criteria.Add(Expression.Ge(param.ParameterName, param.ParameterValue));
break;
case ConstraintType.Equals:
criteria.Add(Expression.Eq(param.ParameterName, param.ParameterValue));
break;
case ConstraintType.Like:
criteria.Add(Expression.Like(param.ParameterName, param.ParameterValue));
break;
}
}
try
{
IList<T> result = criteria.List<T>();
return result;
}
catch
{
//TODO: Implement some exception handling
throw;
}
}
}
The query parameter is a helper object that i use to create criterias and send it to the dal, it looks like this:
public class QueryParameter
{
public QueryParameter(string ParameterName, Object ParameterValue, ConstraintType constraintType)
{
this.ParameterName = ParameterName;
this.ParameterValue = ParameterValue;
this.Constraint = constraintType;
}
public string ParameterName
{
get;
set;
}
public Object ParameterValue
{
get;
set;
}
public ConstraintType Constraint
{
get;
set;
}
}
Now this works well if i'm doing a search like FirstName = "John" , but not when i try to give a parameter like Street = "Some Street". It seems that nhibernate is looking for a street column in the Person table but not in the Address table.
Any idea on how should i change my code for so i could do a proper search? Tips? Maybe some alternatives?
Disclaimer: i'm kind of a noob so please be gentle ;) Thanks, Denis.
© Stack Overflow or respective owner