";包括“;lambda在泛型存储库中

本文关键字:泛型 存储 lambda quot 包括 | 更新日期: 2023-09-27 18:27:55

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

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

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

";包括“;lambda在泛型存储库中

这里有一种方法可以实现

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();

这里有我的通用repoGet方法:

    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;
    }