Use Include() method in repository

后端 未结 3 932
眼角桃花
眼角桃花 2021-01-02 06:04

I have the following with EF 5:

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

This works. Then I tried

相关标签:
3条回答
  • 2021-01-02 06:53

    I used the accepted answer but had to modify it a bit for EntityFramework Core. In my experience I had to keep the chain going or the previous query references were overwritten.

        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;
        }
    
    0 讨论(0)
  • 2021-01-02 06:58

    Try:

    Change

    Expression<Func<T, Boolean>> criteria
    

    To

    Expression<Func<T, object>> criteria
    

    Edit: To Include multiple entities, you need to add an "include" extension:

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

    Then you can use it like this:

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

    Just make sure "repository" return a "DbSet" Object.

    0 讨论(0)
  • 2021-01-02 07:07

    This is what we ended by doing in 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();
            }
    
    0 讨论(0)
提交回复
热议问题