2012-01-24 40 views
4

我想創建一個泛型類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(); 
    } 
} 

回答

3

SelectBy採取Expression<Func<T, bool>>(稱之爲predicate),然後你就可以說,說

x => x.Foo == foo 

例如

var query = this.Entities.Where(predicate); 

可以傳遞的Expression<Func<T, bool>>一個實例。

+0

謝謝賈森! –

相關問題