I am developing an ASP.NET MVC 3 application using C# and Razor.
I have a search form that looks like this:
The search form works in the following way:
The selections in the first drop down related directly to a property in my ADO.NET Entity Framework model class (and therefore directly to a table column).
Users need the ability to explicitly select which property and which matching method when searching, e.g. a user will explicitly search for all matches of process number that equals '132'.
My first approach was to use dynamic linq to construct a Where clause from the search criteria (see my original question). However I'm starting to think that this isn't the best way to do it.
I'm also hoping for a solution that doesn't require me to hard code the result for each property + matching criteria combination.
Any suggestions on how I should implement this search? It doesn't have to be using my current search form, totally open to any other ideas that fit the requirements.
Have you looked into using Lucene.NET for this project? given the nature of your searches it would be very simple to build that using Lucene, as it allows you to combine filters on different columns just like your requirements
You can build expression tree for where predicate using code. For example,
public static IQueryable<T> DynamicWhere<T>(this IQueryable<T> src, string propertyName, string value)
{
var pe = Expression.Parameter(typeof(T), "t");
var left = Expression.Property(pe, typeof(T).GetProperty(propertyName));
var right = Expression.Constant(value);
// Illustrated a equality condition but you can put a switch based on some parameter
// to have different operators
var condition = Expression.Equal(left, right);
var predicate = Expression.Lambda<Func<T, bool>>(condition, pe);
return src.Where(predicate);
}
Use it as Orders.DynamicWhere(searchBy, searchValue)
. You can add one more parameter to accept the operator such as Equals, Greater Than etc to complete the function.
See these links for more info:
http://msdn.microsoft.com/en-us/library/bb882637.aspx
http://msdn.microsoft.com/en-us/library/bb397951.aspx
Also check list of methods on the Expression class to get an idea.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With