2013-07-23 30 views
1

我想從我的通用存儲庫中更改我的通用檢索方法。但我想,而不是通過一個字符串的includeproperties,通過這樣的:params Expression<Func<TEntity, object>>[] includeProperties = null 的事情是,當我把這個方法:EntityFramework通用庫,多個包括?

public virtual IEnumerable<TEntity> Retrieve(Expression<Func<TEntity, bool>> filter = null, params Expression<Func<TEntity, object>>[] includeProperties = null) 

我想例如:TEntityExample.Retrieve(filter: c=>c.Id=Id, includeProperties:c=> c.propertynav1, e=> e.propertynav1.propertynav3, e=> e.Prop4)

或者只是如果不需要導航物業TEntityExample.Retrieve(filter: c=>c.Id=Id)

但不知道爲什麼includeProperties:不工作,不接受,任何人都知道爲什麼,或者如果我做錯了什麼。我想可能性不通過includeProperties或通過指定includeProperties:

public virtual IEnumerable<TEntity> Retrieve(Expression<Func<TEntity, bool>> filter = null, string includeProperties = "") 
      { 
       IQueryable<TEntity> query = _dbSet; 

       if (filter != null) 
       { 
        query = query.Where(filter); 
       } 

       if (!string.IsNullOrEmpty(includeProperties)) 
       { 
        foreach (var includeProperty in includeProperties.Split 
         (new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries)) 
        { 
         query = query.Include(includeProperty); 
        } 
       } 
       return query.ToList(); 
      } 
+0

你在做什麼是一個可怕的做法!我會告訴你很多。您正在爲所有人開放您的API,包括濫用。 – DarthVader

+0

'includeProperties'被鍵入爲一個字符串,但您正在嘗試向其發送lambda表達式。 –

+0

是的,我知道我必須改變字符串類型,也包括他們在我的查詢中的方式......但我想做一個編譯包含..如果你知道我的意思。 – user2528557

回答

10

我做同樣的事情通過它,而是用表情熱切負載。也許這會有所幫助:

public TEntity Item(Expression<Func<TEntity, bool>> wherePredicate, params Expression<Func<TEntity, object>>[] includeProperties) 
    { 
     foreach (var property in includeProperties) 
     { 
      _dbSet.Include(property); 
     } 
     return _dbSet.Where(wherePredicate).FirstOrDefault(); 
    } 
+0

您可以刪除Where並僅使用.FirstOrDefault(wherePredicate); – ssmith

+0

是的,我在這個答案最初發布後的2.5年期間也發現這是真實的。 – MORCHARD