我想从泛型类T创建一个泛型查询。有没有办法使用反射或其他方法来实现类似的查询?
public class DAO<T>
where T : class
{
protected ObjectSet<T> Entities
{
get
{
return myContextThatIsInSomewhere.CreateObjectSet<T>();
}
}
public IList<T> SelectBy(object fields)
{
if (fields == null)
{
throw new ArgumentNullException("fields");
}
var query = from e in this.Entities
select e;
foreach (var field in fields.GetType().GetFields())
{
query = from e in this.Entities
// Do something like that:
where e.(field.Name) == field.GetValue()
select e;
}
return query.ToList();
}
}
让SelectBy
取一个Expression<Func<T, bool>>
(称之为predicate
),然后你就可以说
var query = this.Entities.Where(predicate);
您可以通过说来传递Expression<Func<T, bool>>
的实例
x => x.Foo == foo
例如。