I\'m using now Entity framework- but it\'s a problem \"shared\" between all ORM\'s and even IEnumerable.
Let\'s say I have a method in MVC looks like this:
Your hard coded method is the best method generally.
However you can try to make your life a little easier by writing an appropriate extension method to help keep the code clean.
Try this for example:
public static class QueryableEx
{
public static IQueryable Where(
this IQueryable @this,
bool condition,
Expression> @where)
{
return condition ? @this.Where(@where) : @this;
}
}
Now you could write this code:
[HttpPost]
public ActionResult Foo(FooModel model)
{
using (var context = new Context())
{
var data = context.Foo
.Where(model.Date != null, x => x.Date == model.Date)
.Where(model.Name != null, x => x.Name == model.Name)
.Where(model.ItemCode != null, x => x.ItemCode == model.ItemCode)
.ToList();
return View(data);
}
}
(Please don't forget to dispose of your context or use using to do it for you.)