I was able to get my method (below) to run in LinqPad, but when switching to my actual code (using Entity Framework), I get this error:
"Unable to cast the type 'System.Nullable`1' to type 'System.Object'. LINQ to Entities only supports casting EDM primitive or enumeration types."
The error occurs if I uncomment either of the two commented lines here (the actual error doesn't occur until the last line in the method is run):
public List<LotEquipmentScan> GetLotEquipmentScans(string maximoAssetNumber, decimal? manufacturerId, decimal? partNumber)
{
var predicate = PredicateBuilder.True<LotEquipmentScanRecord>();
// Note: Can't use == in where clause because of the possibility of nulls. That's why we're using object.Equals().
if (maximoAssetNumber != "x") { predicate = predicate.And(scan => object.Equals(scan.MaximoAssetNumber, maximoAssetNumber)); }
//if (manufacturerId != -1) { predicate = predicate.And(scan => object.Equals(scan.RawMaterialLabel.ManufacturerId, manufacturerId)); }
//if (partNumber != -1) { predicate = predicate.And(scan => object.Equals(scan.RawMaterialLabel.PartNumber, partNumber)); }
return Db.LotEquipmentScanRecords.AsExpandable().Where(predicate).ToList().Map();
}
I believe this is happening because manufacturerId and partNumber are nullable decimals. The issue is that those variables can be null, and we even want to filter the results by them being null. Does this just not work with EF, or is there an elegant way around this?
EDIT
To be clear, when manufacturerId is passed in as null, using this line returns five rows (which I can verify by looking at the DB):
if (manufacturerId != -1) { predicate = predicate.And(scan => object.Equals(scan.RawMaterialLabel.ManufacturerId, manufacturerId)); }
Using this line, no rows are returned:
if (manufacturerId != -1) { predicate = predicate.And(scan => scan.RawMaterialLabel.ManufacturerId == manufacturerId); }
The problem is when I pass in a good manufacturerId, then I get the error above.