14

我在 EF 5 中有以下内容:

var a = context.Posts.Include(x => x.Pack).Select(x => x.Pack.Id).ToList();

这行得通。然后我尝试在我的通用存储库中复制它:

public IQueryable<T> Include<T>(Expression<Func<T, Boolean>> criteria) where T : class
{
    return _context.Set<T>().Include(criteria);
}

但在这种情况下,我无法执行以下操作:

var b = repository.Include<Post>(x => x.Pack).Select(x => x.Pack.Id).ToList();

我得到错误:

无法将类型“Data.Entities.Pack”隐式转换为“bool”

我该如何解决这个问题?

我应该在 Include() 方法中进行哪些更改?

4

3 回答 3

16

尝试:

改变

Expression<Func<T, Boolean>> criteria

Expression<Func<T, object>> criteria

编辑:要包含多个实体,您需要添加“包含”扩展名:

public static class IncludeExtension
{
    public static IQueryable<TEntity> Include<TEntity>(this IDbSet<TEntity> dbSet,
                                            params Expression<Func<TEntity, object>>[] includes)
                                            where TEntity : class
    {
        IQueryable<TEntity> query = null;
        foreach (var include in includes)
        {
            query = dbSet.Include(include);
        }

        return query == null ? dbSet : query;
    }
}

然后你可以像这样使用它:

repository.Include(x => x.Pack, x => x.Pack.Roles, ...).Select(x => x.Pack.Id).ToList();

只要确保“存储库”返回一个“DbSet”对象。

于 2012-12-11T02:05:31.457 回答
7

我使用了公认的答案,但不得不为 EntityFramework Core 稍微修改一下。根据我的经验,我必须保持链继续运行,否则之前的查询引用被覆盖。

    public IQueryable<TEntity> Include(params Expression<Func<TEntity, object>>[] includes)
    {
        IIncludableQueryable<TEntity, object> query = null;

        if(includes.Length > 0)
        {
            query = _dbSet.Include(includes[0]);
        }
        for (int queryIndex = 1; queryIndex < includes.Length; ++queryIndex)
        {
            query = query.Include(includes[queryIndex]);
        }

        return query == null ? _dbSet : (IQueryable<TEntity>)query;
    }
于 2016-08-16T17:10:07.073 回答
0

这就是我们在 EF 6 中所做的结束

 public IEnumerable<T> GetIncludes(params Expression<Func<T, Object>>[] includes)
        {
            IQueryable<T> query = table.Include(includes[0]);
            foreach (var include in includes.Skip(1))
            {
                query = query.Include(include);
            }               
            return query.ToList();
        }
于 2018-05-08T00:26:50.340 回答