Search code examples
c#sqlentity-frameworknullreferenceexception

C# - Creating a query in a SQL DB with EntityFrameWork - ERRO -> Value cannot be null. (Parameter 'source')


I'm trying to create the following query in C# with EntityFrameWork:

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

This is the table sample: data

Company class:

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; }

}

This is how C# code is set:

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

The idea is to search for all companies, returning a List, in this table that may contain the 'searchValue', typed by the user.

But this code keeps returning the following error:

`Data is Null. This method or property cannot be called on Null values.

Value cannot be null. (Parameter 'source')`

Expected: Not facing any "NULL" returns anymore.

What did I try: The fixing I found so far, was to completly fill all those "NULL" values in Companies DB Table. But all that values are suppoed to be optional, so they may be NULL some day.


Solution

  • Try changing your class definition to:

    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; }
    
    }
    

    In your data sample, both MWCustomer and ActiveLicense are null, but your class definition has them as non-nullable int. Changing them to int? makes them nullable.

    Also, string? is redundant because that data type is nullable by default. So you can just use string.