I'm developing an application with NHibernate 3.0. I have developed a Repository hat accept a expression to do some filter with QueryOver. My method is something like this:
public IEnumerable<T> FindAll(Expression<Func<T, bool>> filter) {
return Session.QueryOver<T>().Where(filter).List();
}
It works fine. So, I have a Service layer as well, and My methods in this services accepts primitives types, like this:
public IEnumerable<Product> GetProducts(string name, int? stock, int? reserved) {
// how init the expression ?
Expression<Func<Product, bool>> expression = ???;
if (!string.IsNullOrEmpty(name)) {
//add AND condition for name field in expression
}
if (stock.HasValue) {
//add AND condition for stock field in expression
}
if (reserved.HasValue) {
//add AND condition for reserved field in expression
}
return _repository.FindAll(expression);
}
My doubts are:
Is it possible ? Ta add some conditions when necessary (when my parameters has value) ?
Thanks
/// my edits
public ActionResult Index(ProductFilter filter) {
if (!string.IsNullOrEmpty(filter.Name) {
return View(_service.GetProductsByName(filter.Name))
}
// others conditions
}
/// Almost a solution
Expression<Func<Product, bool>> filter = x => true;
if (!string.IsNullOrEmpty(name))
filter = x => filter.Compile().Invoke(x) && x.Name == name;
if (stock.HasValue)
filter = x => filter.Compile().Invoke(x) && x.Stock == stock.Value;
if (reserved.HasValue)
filter = x => filter.Compile().Invoke(x) && x.Reserved == reserved.Value;
return _repository.FindAll(filter);
x=>(!string.IsNullOrEmpty(name)||name==x.Name)&&(stock.HasValue||x.Stock==stock??0) ... etc
What I could add for you is a way to replace the cloture with constants and then shortcut the logical evaluation so that the expression ends up as short as you want.