我正在尝试查找哪些字段包含或包含某些内容的客户端。如果我对谓词进行硬编码,一切都会起作用,但是当我通过谓词时,它将抛出NullReferenceException
。
回购代码:
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;
}
}
服务代码:
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;
}
}
该代码有什么问题?
答案 0 :(得分:1)
从以下位置更改方法中参数的类型
Func<Contractor, bool> predicate
到
Expression<Func<Contractor, bool>> predicate
另请参阅相关问题Why would you use Expression<Func<T>> rather than Func<T>?