"包含" lambda在通用存储库中

时间:2014-10-27 14:39:52

标签: c# lambda entity-framework-6

我遵循存储库模式,我的通用存储库类中有以下方法:

    public virtual T Get(Expression<Func<T, bool>> where)
    {
        return dbset.Where(where).FirstOrDefault<T>();
    }

我想添加一个lambda表达式来包含导航属性。有可能吗?

2 个答案:

答案 0 :(得分:0)

这是你可以做到的一种方式

public virtual IQueryable<T> Include(this IQueryable<T> qry, params string[] includes)
{
    foreach(var inc in includes)
         qry = qry.Include(inc);
    return qry;
}

使用示例:

var list = context.Products.Where(x => x.ProductID == 1).Include("Items", "Person").Single();

答案 1 :(得分:0)

我的通用仓库获取方法:

    public virtual IQueryable<TEntity> Get(
        Expression<Func<TEntity, bool>> filter = null,
        Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null,
        string includeProperties = "")
    {
        IQueryable<TEntity> Query = DbSet;

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

        if (!string.IsNullOrEmpty(includeProperties))
        {
            foreach (string IncludeProperty in includeProperties.Split(new[] {','}, StringSplitOptions.RemoveEmptyEntries))
            {
                Query = Query.Include(IncludeProperty);
            }
        }

        if (orderBy != null)
        {
            return orderBy(Query);
        }
        return Query;
    }