Skip to content

Allow creating an Expression<Func<>> instead of a IQueryable Projection #733

Description

@Tvde1

It is possible to get a IQueryable<B> ProjectToB(IQueryable<A> query) which can be used as

context.ASet.ProjectToB().ToListAsync();

Is your feature request related to a problem? Please describe.

We have a generic class like follows:

class BaseRepository<TEntity, TModel>
{
    public BaseRepository(DbSet<TEntity> dbSet, Func<IQueryable<TEntity>, IQueryable<TModel>> projectToModel) { ... }

    public async Task<List<TModel>> GetAll()
    {
        return await _projectToModel(
                _dbSet.Where(x => x.SomeCondition)
            )
            .Where(x => x.IsSomething)
            .ToListAsync();
    }
}

class UserRepository : BaseRepository<UserEntity, UserModel>
{
    public UserRepository(DbContext c) : base(c.Users, UserMapper.ProjectToModel) {}
}

static partial class UserMapper
{
    public static partial IQueryable<UserModel> ProjectToModel(this IQueryable<UserEntity> q);
}

Describe the solution you'd like
I would prefer being able to create an Expression<Func<A, B>> and give it to my base repository.

class BaseRepository<TEntity, TModel>
{
    public BaseRepository(DbSet<TEntity> dbSet, Expression<Func<TEntity, TModel>> projectToModel) { ... }

    public async Task<List<TModel>> GetAll()
    {
        return await _dbSet
            .Where(x => x.SomeCondition)
            .Select(_projectToModel)
            .Where(x => x.IsSomething)
            .ToListAsync();
    }
}

class UserRepository : BaseRepository<UserEntity, UserModel>
{
    public UserRepository(DbContext c) : base(c.Users, UserMapper.CreateToModelProjection()) {}
}

static partial class UserMapper
{
    public static partial Expression<Func<UserModel, UserEntity>> CreateToModelProjection()
}

This will make the query cleaner and easier to read.

Describe alternatives you've considered
The aforementioned code works, but I'd prefer the new variant.

Additional context
I'm happy to hear your opinions on this matter.

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions