I'm working with Entity Framework and Silverlight (RIA) and am looking at creating a function to expand on the CRUD to allow for the user to specify a specific column name, and then a matching value to pinpoint an exact record... The code would look something like this...
public IQueryable<Category> GetCategory(string theColumn, string theCriteria)
{
return this.ObjectContext.Categories
.Where(c => c.theColumn = theCriteria);
}
The similar working function to get ALL categories... (Created by building after associating a data model)
public IQueryable<Category> GetCategories()
{
return this.ObjectContext.Categories;
}
Thanks in advance!
I have built something similar to what you are looking to construct. I built around using Expression trees from System.Linq.Expressions. So I would suggest that you build your where predicate using an expression tree where the predicate has the signature of Expression<Func<T,bool>>
.
Some pseudo code below where T is a WCF RIA entity:
public static class QueryHelper
{
public static Expression<Func<T, bool>> ToPredicate<T> ( string propertyName, dynamic criteria )
{
ParameterExpression pe = Expression.Parameter( typeof( T ), "t" );
Expression np = Expression.Property( pe, propertyName );
ConstantExpression value = Expression.Constant( criteria );
Expression e1 = Expression.Equal( np, value );
var filter = Expression.Lambda<Func<T, bool>>( e1, pe );
return filter;
}
}
Which could then be used like:
var selector = QueryHelper.ToPredicate<Category>("theColumn", "hello");
return this.ObjectContext.Categories.Where(selector);
LoadOperation<Employee> loader = context.Load( context.GetEmployeesQuery()
.Where( selector ) );
loader.Completed += (op) =>
{
if ( !op.HasErrors)
{
}
};
Or
var selector = QueryHelper.ToPredicate<Category>("theColumn", true);
return this.ObjectContext.Categories.Where(selector);
One thing to note is the line Expression e1 = Expression.Equal( np, value ); in the function. You could extend this function to do >, <, =>, etc but you would need to check that the property type you were using supported the operator.
Hope this helps.