Home > Back-end >  lambda expression with nullable value - always false since the value of type Guid is never equal to
lambda expression with nullable value - always false since the value of type Guid is never equal to

Time:11-20

public class Car
{
    public int Id {get; set;}
    public Guid? OwnersId { get; set; }
    ...
}

I'm trying to fetch all car data upon criteria

List<Car> cars = await carsContext.Query(x=>x.Id== model.CarId && x.OwnersId.Value == null);

The result of the expression is always false since the value of type Guid is never equal to 'null' of type 'Guid?'

CodePudding user response:

Value property of Nullable<T> struct returns value of the underlying type (Guid in your case) which can not be null. Compare the OwnersId itself to null:

List<Car> cars = await carsContext
    .Query(x => x.Id == model.CarId && x.OwnersId == null);

Another option is to check HasValue property:

List<Car> cars = await carsContext
    .Query(x => x.Id == model.CarId && !x.OwnersId.HasValue);

Though if this will translate into valid SQL depends on the ORM you are using.

CodePudding user response:

The 'Value' property will never be null. If the OwnersId is null then calling .Value would throw an exception. You should check against HasValue. So you can do this:

List<Car> cars = await carsContext.Query(x=>x.Id== model.CarId && !x.OwnersId.HasValue);
  • Related