2013-07-23 28 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