C#C
C#10mo ago
Hulkstance

Possible NullReferenceException

I've created the following extension method:
public static class QueryableExtensions
{
    public static IQueryable<TSource> WhereIf<TSource>(
        this IQueryable<TSource> source,
        bool condition,
        Expression<Func<TSource, bool>> predicate)
    {
        ArgumentNullException.ThrowIfNull(source);
        ArgumentNullException.ThrowIfNull(predicate);
        
        return condition
            ? source.Where(predicate)
            : source;
    }

    public static IQueryable<TSource> WhereIfElse<TSource>(
        this IQueryable<TSource> source,
        bool condition,
        Expression<Func<TSource, bool>> predicateIf,
        Expression<Func<TSource, bool>> predicateElse)
    {
        ArgumentNullException.ThrowIfNull(source);
        ArgumentNullException.ThrowIfNull(predicateIf);
        ArgumentNullException.ThrowIfNull(predicateElse);
        
        return condition
            ? source.Where(predicateIf)
            : source.Where(predicateElse);
    } 
}


public sealed class GetAllBotsQueryHandler(IAppDbContext dbContext)
    : IRequestHandler<GetAllBotsQuery, IReadOnlyList<Bot>>
{
    public async Task<IReadOnlyList<Bot>> Handle(GetAllBotsQuery request, CancellationToken cancellationToken)
    {
        return await dbContext.Bots
            .AsNoTracking()
            .Include(x => x.User)
            .Include(x => x.Exchange)
            .WhereIf(request.UserId.HasValue, x => x.UserId == request.UserId.Value)
            .ToListAsync(cancellationToken);
    }
}


request.UserId.Value:
Nullable value type can be null

Why it doesn't notice the request.UserId.HasValue? Is there an attribute I have to add or smt
Was this page helpful?