.net mvc - How to make class method parameter (IQueryable) to be nullable

how to check null value in linq query in c#
defaultifempty
how to check null value in lambda query in c#
linq select where not null or empty
how to check datatable column value is null or empty in c# linq
linq left join
c# linq select check for null
firstordefault null

I have a class method that receives a queryable parameter:

public IQueryable<Company> getEmpresasVisiblesUsuario(IQueryable<Company> companies, bool onlyActive = true)
{
    /*
    if (companies == null) {
        companies = db.companies;
    }
    */

    int userId = HttpContext.Current.User.Identity.GetUserId<int>();
    companies = companies.Where(s => s.id_user == userId);

    if (onlyActive) {
        companies = companies.Where(e => e.active);
    }   
    return companies;
}

This is working ok, but now I need the parameter 'companies' to be optional... how can I do that? I have tried with IQueryable? companies, but that gives an error:

the type IQueryable<Company> must be a non-nullable value type in order to use it as a parameter 'T' in the generic type or method 'Nullable<T>'

Give companies parameter a default value (ie. null)

public IQueryable<Company> getEmpresasVisiblesUsuario(IQueryable<Company> companies = null, bool onlyActive = true)

then your method can be called as follows

getEmpresasVisiblesUsuario(companies, false);
getEmpresasVisiblesUsuario(companies);
getEmpresasVisiblesUsuario(onlyActive: false);

Queryable.DefaultIfEmpty Method (System.Linq), DefaultIfEmpty<TSource>(IQueryable<TSource>). Returns the elements of the specified sequence or the type parameter's default value in a singleton collection if  The set of methods declared in the Queryable class provides an implementation of the standard query operators for querying data sources that implement IQueryable<T>. The standard query operators are general purpose methods that follow the LINQ pattern and enable you to express traversal, filter, and projection operations over data in any .NET

You can do overloads of your method so:

public IQueryable<Company> getEmpresasVisiblesUsuario(bool onlyActive = true)
{
     return getEmpresasVisiblesUsuario(db.companies, onlyActive);
}

public IQueryable<Company> getEmpresasVisiblesUsuario(IQueryable<Company> companies, bool onlyActive = true)
{
    int userId = HttpContext.Current.User.Identity.GetUserId<int>();
    companies = companies.Where(s => s.id_user == userId);

    if (onlyActive) {
        companies = companies.Where(e => e.active);
    }   
    return companies;
}

Handle null values in query expressions (LINQ in C#), Example. You can code defensively to avoid a null reference exception as shown in the following example: C# Copy. Nullable reference types. 04/21/2020; 7 minutes to read +6; In this article. C# 8.0 introduces nullable reference types and non-nullable reference types that enable you to make important statements about the properties for reference type variables: A reference isn't supposed to be null. When variables aren't supposed to be null, the compiler

Em, just add null to the parameter:

public IQueryable<Company> getEmpresasVisiblesUsuario(IQueryable<Company> companies = null, bool onlyActive = true)

ASP.NET MVC - Generic filtering based on expressions, The repository has a method which returns an IQueryable: Parameter(typeof(T)​, "p"); var property = this. if (searchExpression == null) { return query; } else { var predicate The base class takes care of creating the MemberExpression and also adds null checks to avoid null reference exceptions. Nullable types can only be used with value types. The Value property will throw an InvalidOperationException if value is null; otherwise it will return the value. The HasValue property returns true if the variable contains a value, or false if it is null. You can only use == and != operators with a nullable type.

[SOLVED], One of the fields in the query's anonymous type did not exist in MyType . I discovered this while I was creating a view model to use in this method. In this article, I am going to discuss How to make Optional Parameters in C# with some examples. Please read our previous article, where we discussed Automappers in C#. This is also one of the most frequently asked interview questions. So here we will discuss the different options that are available in C# to make the method parameters as optional.

Null or empty object when LINQ to Entities query returns nothing , An empty set is a reasonable answer; it means you don't have any of the things Create a separate method which allow you to check if the object exists Returns a boolean which indicates if the object exists and places the object (if present) in an out parameter. return an "empty" instance of the class. The controller class locates the action method and determines any parameter values for the action method, based on the RouteData instance and based on the form data. If the parameter value cannot be parsed, and if the type of the parameter is a reference type or a nullable value type, null is passed as the parameter value.

Filter data with optional parameters, This is not consistant and it's difficult to get help with local names. public class FilterVM { public string Voornaam { get; set; } public string IEnumerable<​Registration> Filter(FilterVM filterVM) { return null } Use this extension in method: private IQueryable<Registration> Filter(FiterVM filter) { return All() . So now let's look into why we should not return IQueryable from a Repository class method. By visiting this link from MSDN we can have an excellent explanation of what IQueryable<T> is. public interface IQueryable< out T> : IEnumerable<T>, IEnumerable, IQueryable. First of all it is an interface that inherits from IEnumerble<T> and IEnumerable.

Comments
  • companies = companies?.Where(..)
  • So simple, thank you.I was pretty sure i had tried that with no success, but it seems I was wrong. I will choose this answer as the correct one just for its simplicity, although I think all answers are correct.