I am using the Entity framework now, but this is a problem "split" between all ORMs and even IEnumerable.
Say I have a method in MVC that looks like this:
[HttpPost] public ActionResult Foo(FooModel model) { var context = new Context(); -- The EF session var data = context.Foo.Where(???).ToList(); return View(data); }
I want to request a context based on an input parameter, for example:
var data = context.Foo.Where(x => x.Date == model.Date && x.Name == model.Name && x.ItemCode = model.ItemCode).ToList();
But this is more complicated, because if one of the above parameters ( Date \ Name \ ItemCode ) is null, I do not want to include it in the request.
If I have hard code, it might look something like this:
var query = context.Foo; if (model.Date != null) query =query.Where(x => x.Date == model.Date); if (model.ItemCode != null) query =query.Where(x => x.ItemCode == model.ItemCode); ...
There should be an easier way than this. I need a way to generate an expression like Expression<T, bool> , which will be used in the Where method.
[HttpPost] public ActionResult Foo(FooModel model) { var context = new Context(); -- The EF session var data = context.Foo.Where(THE_EXPRESSION).ToList(); return View(data); }
Is there a built-in way to create this expression? Is there a package in nuget that does this?
Update: There can be more than 30 posts in an entity model; record 30 times Where for each request there may be a pain in the neck:
.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();