Miguel Moura Miguel Moura - 1 year ago 191
C# Question

Use Include() method in repository

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 to replicate this in my generic repository:

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

But in this case I am not able to do the following:

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

I get the error:

Cannot implicitly convert type 'Data.Entities.Pack' to 'bool'

How can I solve this?

What should I change in my Include() method?

Answer Source



Expression<Func<T, Boolean>> criteria


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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download