需要更好的EF FindAll()存储库方法

本文关键字:存储 方法 FindAll 更好 EF | 更新日期: 2023-09-27 18:01:15

我从以前的开发人员那里继承了一个Generic Repository Pattern。它似乎工作正常,只是我希望FindAll((方法能够包括导航属性,而不仅仅是第一级。

签名如下:

public IEnumerable<T> FindAll(List<string> includes, Expression<Func<T, bool>> where, IEnumerable<Sorting> orderBy)

includes属性允许我传入要加载的导航属性,但仅适用于顶级存储库对象。为第一级的子导航属性传入导航属性的名称没有任何效果。

以下是完整的方法:

        public IEnumerable<T> FindAll(List<string> includes, Expression<Func<T, bool>> where, IEnumerable<Sorting> orderBy)
    {
        IQueryable<T> query = _dbSet;
        if (includes != null)
            query = includes.Aggregate(query, (current, include) => current.Include(include));
        if (where != null)
            query = (DbQuery<T>)query.Where(where);
        if (orderBy != null)
        {
            var first = true;
            foreach (var item in orderBy)
            {
                var propertyName = string.IsNullOrEmpty(item.Field) ? string.Empty : item.Field.Trim();
                var dir = string.IsNullOrEmpty(item.Dir) ? string.Empty : item.Dir.Trim();
                if (string.IsNullOrEmpty(propertyName))
                    throw new ArgumentException("Invalid Property. Order By Format: Property, Property2 ASC, Property2 DESC");
                var descending = false;
                if (!string.IsNullOrEmpty(dir))
                    descending = dir.Equals("desc", StringComparison.OrdinalIgnoreCase);
                if (first)
                    query = descending ? query.OrderByDescending(propertyName) : query.OrderBy(propertyName);
                else
                    query = descending ? query.ThenByDescending(propertyName) : query.ThenBy(propertyName);
                first = false;
            }
        }
        return query;
    }

此外,如果有一个更好的方法,那么请与我分享。

谢谢你的帮助。

Earl

需要更好的EF FindAll()存储库方法

您仍然可以使用与现有方法相同的方法。

只需在Include字符串中包含第二级属性的名称,如下所示:

"FirstLevelProperty.SecondLevelProperty"