在存储库中使用Include()方法

时间:2012-12-11 01:50:40

标签: c# .net entity-framework compiler-errors

我在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()方法应该更改什么?

3 个答案:

答案 0 :(得分:14)

尝试:

更改

Expression<Func<T, Boolean>> criteria

Expression<Func<T, object>> criteria

编辑: 要包含多个实体,您需要添加一个&#34; include&#34;扩展:

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

确保&#34;存储库&#34;返回&#34; DbSet&#34;宾语。

答案 1 :(得分:2)

我使用了接受的答案,但不得不为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;
    }

答案 2 :(得分: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();
        }