谓词上的“对象引用未设置为对象的实例”

时间:2019-08-13 15:52:40

标签: c# sql entity-framework contains 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;
    }
}

该代码有什么问题?

1 个答案:

答案 0 :(得分:1)

从以下位置更改方法中参数的类型

Func<Contractor, bool> predicate

Expression<Func<Contractor, bool>> predicate

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