我想从泛型类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();
}
}
答案 0 :(得分:3)
让SelectBy
取Expression<Func<T, bool>>
(称之为predicate
)然后你就可以说
var query = this.Entities.Where(predicate);
您可以通过说
传递Expression<Func<T, bool>>
的实例
x => x.Foo == foo
例如。