I want to create a method like this:
var result = database.Search(x=>x.Name, \"Entity Name field value\");
result = database.Search
You can turn a selector and value into a predicate using Expression.Equal
:
static IQueryable Search(
this IQueryable source,
Expression> selector,
TValue value)
{
var predicate = Expression.Lambda>(
Expression.Equal(
selector.Body,
Expression.Constant(value, typeof(TValue))
), selector.Parameters);
return source.Where(predicate);
}
Then you just need to do something like:
var result = database.SomeEntities.Search(x => x.SomeProp, "value");
If you want to do it from the database, then that depends on what the database is; for example, with LINQ-to-SQL you could add an additional method:
static IQueryable Search(
this System.Data.Linq.DataContext database,
Expression> selector,
TValue value) where TSource : class
{
IQueryable source = database.GetTable();
return Search(source, selector, value);
}
and use:
var result = database.Search(x => x.SomeProp, "value");
frankly I think it is clearer to use the database.SomeEntities
version, though.