【问题标题】:C# Query when any of the condition is not null当任何条件不为空时 C# 查询
【发布时间】:2019-02-18 18:43:20
【问题描述】:

我想在满足任一条件时查找数据库中的数据。

粘贴我的代码,这样会更清楚

    [HttpGet]
    [Route("")]
    public IEnumerable<User> GetUsers(string FirstName = null, string LastName = null, int Year = 0, int Month = 0)
    {

        var users = _context.Users.AsQueryable();
        if (FirstName != null || LastName != null || Year != 0 || Month != 0)
        {
            users = _context.Users.Where(u => (u.CreatedAt.Year == Year) && (u.CreatedAt.Month == Month));
        }
        else
        {
            users = _context.Users;
        }

        return users.ToList();

    }

这段代码在数据库中做一个简单的搜索

where year == createdAt.year &&
              month == createdAt.month && 
              LastName == abc && 
              FirstName == abc

但是,如果其中一个条件是 0/null,那么数据库将不会返回任何内容,因为没有月/年 == 0 或名字/姓氏 == null;我想要的是,如果年/月/姓/名是 0/null,则忽略它并检查其他条件。

有什么想法吗?

【问题讨论】:

    标签: c# sql linq lambda


    【解决方案1】:
    // first style
    users = _context.Users.Where(u => 
        (Year != 0 ? u.CreatedAt.Year == Year : true) &&
        (Month != 0 ? u.CreatedAt.Month == Month : true) &&
        (FirstName != null ? u.FirstName == FirstName : true) &&
        (LastName != null ? u.LastName == LastName : true));
    // second style
    users = _context.Users.Where(u => 
        (Year == 0 || u.CreatedAt.Year == Year) &&
        (Month == 0 || u.CreatedAt.Month == Month) &&
        (FirstName == null || u.FirstName == FirstName) &&
        (LastName == null || u.LastName == LastName));
    

    我认为您应该像这样分别检查每个条件。 例如,当 Year != 0 且未设置所有其他参数时,您的原始代码将不返回任何内容。

    【讨论】:

    • 第二种样式是正确答案。第一个将给出一些关于简化三元表达式的警告。谢谢!
    【解决方案2】:

    您可以将逻辑添加到 LINQ 查询以检查条件。

    users = _context.Users.Where(x => x.Id !=0 
                                   && x.FirstName != null 
                                   && x.FirstName != null 
                                   && x.Year != 0 
                                   && x.Month != 0)
                                  .ToList(); 
    

    【讨论】:

    • 这将搜索所有不为空的数据对吗?我想让它使用我给定的参数搜索数据库。为了更好地理解,我已经添加了上面的整个方法。
    • 所以这段代码在数据库中做一个简单的搜索,其中 year == createdAt.year && month == createdAt.month。但是,如果条件之一为 0,则数据库将不返回任何内容,因为没有月/年 == 0;我想要的是,如果年/月为 0,则忽略它并检查其他条件。
    【解决方案3】:

    试试这个users = _context.Users.Where(x => && (x.FirstName != null || x.FirstName == FirstName) && (x.Year == 0 || x.Year == Year) && (x.Month == 0 || x.Month == Month) .ToList();

    【讨论】:

    • 这是一个非常好的提示,谢谢。但是,它需要进行一些修改才能使其正常工作。我们应该检查 Month == 0 || 而不是 x.Year!=0 x.Month == 月份,这样只要月份为 0,就为真,不检查第二个,对吧?
    • 是的,两周前我在做过滤器时也遇到了同样的情况。告诉我们它是否有效:D
    • 我试过,在你的解决方案中,你检查了 (x.year/month/firstname != null/0),但是你没有检查参数 year/month/firstname == 0/null,然后年/月/名仍然可以为0并传入。然后它仍然不起作用。 ivooQ 的答案有效。看看他的第二种风格。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多