I'm using the Generic Repository pattern on my project and I have the following method that retrieves data according to the parameters provided :
public virtual async Task<IReadOnlyCollection<TEntity>> GetAsync(
Expression<Func<TEntity, bool>> filter = null, Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null)
{
IQueryable<TEntity> query = dbSet;
if (filter != null)
{
query = query.Where(filter);
}
if (orderBy != null)
{
query = orderBy(query);
}
return await query.ToListAsync();
And I'm trying to add another paramter to apply a DistinctBy filter and this's what I did :
public virtual async Task<IReadOnlyCollection<TEntity>> GetAsync(
Expression<Func<TEntity, bool>> filter = null, Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null,
Expression<Func<TEntity, object>> distinctBy = null)
{
IQueryable<TEntity> query = dbSet;
if (filter != null)
{
query = query.Where(filter);
}
if (orderBy != null)
{
query = orderBy(query);
}
if (distinctBy != null)
{
query = query.DistinctBy(distinctBy);
}
return await query.ToListAsync();
}
But it's not working and I dont understand what I'm doing wrong. Thsi gives me the following exception :
The LINQ expression 'DbSet...' could not be translated. Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to 'AsEnumerable', 'AsAsyncEnumerable', 'ToList', or 'ToListAsync'
Thank you.
Edit :
I created a new class in which i put the DistinctBy extension method I'm going to use :
public static class EntityFrameWorkExtensions
{
public static IQueryable<TSource> DistinctByPlus<TSource, TKey>(this IQueryable<TSource> source, Expression<Func<TSource, TKey>> keySelector)
{
return source.GroupBy(keySelector)?.Select(x => x.FirstOrDefault());
}
}
And on my GenericRepository class I edited the signature of my method and I used this new extension method like this :
public virtual async Task<IReadOnlyCollection<TEntity>> GetAsync(
Expression<Func<TEntity, bool>> filter = null, Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null,
Expression<Func<TEntity, object>> distinctBy = null)
{
IQueryable<TEntity> query = dbSet;
if (filter != null)
{
query = query.Where(filter);
}
if (orderBy != null)
{
query = orderBy(query);
}
if (distinctBy != null)
{
query = query.DistinctByPlus(distinctBy);
}
int count = query.Count();
return await query.ToListAsync();
}
Here's my call to this method :
var data = await _unitOfWork.UserRepository.GetAsync(x => x.userId == id, distinctBy: o => o.SupervisorId);
But now this's giving me another error :
Nullable object must have a value.
This exception is thrown exactly after int count = query.Count();. I know this line looks useless but I will need it later.
Even though none of my database table records have SupervisorId null and when I remove the distinctBy the call works perfectly.