"Object reference not set to an instance of an object" 谓词

"Object reference not set to an instance of an object" on predicate

我正在尝试查找哪些字段具有或包含某些内容的客户。如果我对谓词进行硬编码,一切都会正常,但是当我传递谓词时,它会抛出 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;
    }
}

该代码有什么问题?

更改方法中参数的类型
Func<Contractor, bool> predicate

Expression<Func<Contractor, bool>> predicate

另见相关问题Why would you use Expression<Func<T>> rather than Func<T>?