首页 > 解决方案 > 当任何条件不为空时 C# 查询

问题描述

当任何一个条件满足时,我想在数据库中查找数据。

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

    [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#sqllinqlambda

解决方案


// 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 且未设置所有其他参数时,您的原始代码将不返回任何内容。


推荐阅读