简体   繁体   中英

Entity Framework throws an error when executing a lambda expression

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM