Entity Framework throws an error when executing a lambda expression

asp.net c# entity-framework-core

Question

I have this piece of code for fetching and filtering results of products from a database:

if (userParams.MinPrice > 0 && userParams.MaxPrice != 999999999) 
{
    products = products.Where(p => (p.Price >= userParams.MinPrice) && 
                                   (p.Price <= userParams.MaxPrice));
}

This gets executed successfully when only the userParams.MinPrice is provided but fails when userParams.MaxPrice is provided.

The error that I get is this.

An unhandled exception has occurred while executing the request.

System.InvalidOperationException: An exception was thrown while attempting to evaluate a LINQ query parameter expression. To show additionalinformation call EnableSensitiveDataLogging() when overriding DbContext.OnConfiguring.

System.NullReferenceException: Object reference not set to an instance of an object.

at lambda_method(Closure )
at Microsoft.EntityFrameworkCore.Query.ExpressionVisitors.Internal.ParameterExtractingExpressionVisitor.Evaluate(Expression expression, String& parameterName).

Does anyone know the solution to this? Please help

1
0
1/19/2019 9:40:19 PM

Accepted Answer

It's pretty simple, your error explains it. userParams.MaxPrice is null. So you need to add null checking to it. A simple way would be to change your query to:

if (userParams.MinPrice > 0 && userParams.MaxPrice != null && userParams.MaxPrice != 999999999) 
{
    products = products.Where(p => (p.Price >= userParams.MinPrice) && 
                                   (p.Price <= userParams.MaxPrice));
}

Though depending on your logic you may need to change things up slightly. The key point is to not assume that a property has a value, if it's nullable, then you need to first validate it's not null then check it.

Should also add that you could in theory do userParams.MaxPrice.GetValueOrDefault() != 999999999 assuming that this is a nullable int or something like that.

0
1/20/2019 12:11:33 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow