c# - .net mvc - 如何使类方法参数 (IQueryable) 可以为空

标签 c# .net asp.net-mvc iqueryable

我有一个接收可查询参数的类方法:

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

这工作正常,但现在我需要参数“companies”是可选的……我该怎么做? 我试过 IQueryable?公司,但这给出了一个错误:

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>'

最佳答案

您可以重载您的方法:

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

关于c# - .net mvc - 如何使类方法参数 (IQueryable) 可以为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54145992/

相关文章:

c# - Entity Framework 模型的两个引用冲突

c# - 从目录中选择随机文件

sql-server - 用户“IIS APPPOOL\”登录失败

c# - 传递到字典中的模型项是 .. 类型的,但是这个字典需要一个类型的模型项

c# excel 插入检查工作表是否存在

c# - 如何根据某些配置对 WPF View 进行细微修改

c# - 向 WebAPI 添加新方法会出现 "multiple actions"错误

c# - 删除发布版本的 NUnit 引用

c# - Automapper:更新属性值而不创建新对象

asp.net-mvc - ASP.NET 5 IsPost 消失了吗?