Search Criteria and NULL

I use the following method template in my web API to search for objects based on a set of criteria:

public IEnumerable<Employee> Search(SearchCriteria searchCriteria)
{
    var employees = _dbContext.Employees;

    if(searchCriteria.Age.HasValue)
    {
        employees = employees.Where(e => e.Age == searchCriteria.Age.Value);
    }

    if(searchCriteria...)
    {
        employees = employees.Where(e => ...);
    }

    return employees;
}

If no search criteria is specified, then the property of the SearchCriteria object will be null, and I just don’t filter based on this criteria. If specified, it will be relevant and will be used for filtering.

The problem, from a design point of view, is that if I really want to employeeshave no age, I just can’t do it this way, as I use nullto determine if I will use this criterion.

What other approach should I study to cover both cases?

, URI , -API , , ?

mysite.com/api/employee?keyword=a&age=null

mysite.com/api/employee?keyword=a
+4
3

, SearchCriteria. Nullable<T>, Nullable<int> Age, , , .

, ;)

+2

, , -1 , :

    if(searchCriteria.Age.HasValue){
        if(searchCriteria.Age != -1)
            employees = employees.Where(e => e.Age == searchCriteria.Age.Value);
        }
        else{
            employees = employees.Where(e => e.Age == null);
    }
}
0

There is no need to use conditional validation. If the age database value can be zero, then your domain object must be int?, and in this case Ageyou can use without .Value.

public IEnumerable<Employee> Search(SearchCriteria searchCriteria)
{
  var employees = _dbContext.Employees.Where(e => e.Age == searchCriteria.Age);

  if(searchCriteria...)
  {
    employees = employees.Where(e => ...);
  }

  return employees;
}
0
source

Source: https://habr.com/ru/post/1569335/


All Articles