I'm trying to find clients which fields have or contain something. Everything works if I hard code predicate, but when I pass predicate it throws a NullReferenceException
.
Repo code:
public IEnumerable<Contractor> Find(Func<Contractor, bool> predicate)
{
var test = db.Contractors.Where(x => x.NIP.Contains("7822574676")).ToList(); //this is correct
try
{
return db.Contractors.Where(predicate).ToList(); // this gives exception
}
catch (Exception ex)
{
return null;
}
}
Service code:
public IEnumerable<ContractorShortDataDTO> FindByNIP(string NIP)
{
try {
return Database.Contractors.Find(x => x.NIP.Contains(NIP)).Select(x =>
new ContractorShortDataDTO()
{
NIP = x.NIP,
CompanyName = x.CompanyName,
ID = x.ID
}).AsEnumerable();
} catch(Exception ex) {
return null;
}
}
What is wrong with that code?
Change the type of the argument in the method from
Func<Contractor, bool> predicate
to
Expression<Func<Contractor, bool>> predicate
See also related question Why would you use Expression<Func<T>> rather than Func<T>?