我想从泛型类 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
例如。
关于c# - 是否可以使用反射从通用实体访问属性(按名称)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8988221/