I want to compare nullable decimal values from the database in entity framework LINQ.
I tried these approaches:
return Db.Products.Any(x =>
(x.WholeSalePriceVATOut== null && product.WholeSalePriceVATOut== null) ?
true : (x.WholeSalePriceVATOut== null || product.WholeSalePriceVATOut== null) ?
false : (Decimal.Compare((decimal)x.WholeSalePriceVATOut, (decimal)product.WholeSalePriceVATOut) == 0) ? true : false)
And
return Db.Products.Any(x =>
((x.WholeSalePriceVATOut.HasValue) ? (decimal?)Math.Round((decimal)x.WholeSalePriceVATOut, 3) : null) == ((product.WholeSalePriceVATOut.HasValue) ? (decimal?)Math.Round((decimal)product.WholeSalePriceVATOut, 3) : null))
And
return Db.Products.Any(x =>
Decimal.Compare((x.WholeSalePriceVATOut == null) ? -1 : (decimal)x.WholeSalePriceVATOut, (product.WholeSalePriceVATOut == null) ? -1 : (decimal)product.WholeSalePriceVATOut) == 0) ? true : false)
All of these examples throw:
Nullable object must have a value
Is there some elegant way to compare nullable decimal?
Just use Nullable.Equals()
. The following should be sufficient:
return Db.Products.Any(p =>
Nullable.Equals(p.WholeSalePriceVATOut, product.WholeSalePriceVATOut));
When EF converts that into SQL, the relevant part of the SQL will be something like:
WHERE (`Product`.`WholeSalePriceVATOut` = @p__0) OR
((`Product`.`WholeSalePriceVATOut` IS NULL) AND (@p__0 IS NULL))))
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.