代码之家  ›  专栏  ›  技术社区  ›  Jean Tosta

C#-使用EntityFrameWork-ERRO->Value在SQL DB中创建查询时,值不能为null。(参数“source”)

  •  2
  • Jean Tosta  · 技术社区  · 1 年前

    我正尝试使用EntityFrameWork在C#中创建以下查询:

    SELECT * FROM Companies WHERE Name LIKE '%(searchValue)%';

    这是表格示例: data

    公司类别:

    public class Company {     
        [Key]     
        public int ID { get; set; }     
        public string? Name { get; set; }     
        public int IndustrySegment { get; set; }     
        public string? Departments { get; set; }     
        public int MWCustomer { get; set; }     
        public int ActiveLicense { get; set; }     
        public string? Employees { get; set; }     
        public string? Selections { get; set; }
    
    }
    

    C#代码是这样设置的:

    var context = new FILTER_SYSTEM_CONTEXT();
    var connectionCompanies = new DAL_SYSTEM<Company>(context);
    var searchByName = connectionCompanies
        .Where(a => (a.Name ?? "").Contains(searchValue))
        .ToList();`
    

    这个想法是搜索所有公司,返回一个列表,该列表可能包含用户键入的“searchValue”。

    但这段代码不断返回以下错误:

    `数据为空。不能对Null调用此方法或属性 价值观。

    值不能为null。(参数“source”)`

    预期: 不再面临任何“NULL”返回。

    我尝试了什么: 到目前为止,我发现的修复方法是完全填充Companies DB表中的所有“NULL”值。但所有这些值都是可选的,所以总有一天它们可能会为NULL。

    1 回复  |  直到 1 年前
        1
  •  1
  •   devlin carnate    1 年前

    尝试将类定义更改为:

    public class Company {     
        [Key]     
        public int ID { get; set; }     
        public string Name { get; set; }     
        public int IndustrySegment { get; set; }     
        public string Departments { get; set; }     
        public int? MWCustomer { get; set; }     
        public int? ActiveLicense { get; set; }     
        public string Employees { get; set; }     
        public string Selections { get; set; }
    
    }
    

    在您的数据示例中,两者 MWCustomer ActiveLicense 为null,但您的类定义将它们设置为不可为null int 。将它们更改为 int? 使它们可以为空。

    也, string? 是冗余的,因为默认情况下该数据类型可以为空。所以你可以直接使用 string .