C#当任何条件不为空时进行查询
我想在任何一个条件满足时在数据库中查找数据 粘贴我的代码,使其更清晰C#当任何条件不为空时进行查询,c#,sql,linq,lambda,C#,Sql,Linq,Lambda,我想在任何一个条件满足时在数据库中查找数据 粘贴我的代码,使其更清晰 [HttpGet] [Route("")] public IEnumerable<User> GetUsers(string FirstName = null, string LastName = null, int Year = 0, int Month = 0) { var users = _context.Users.AsQueryable();
[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();
}
但是,如果其中一个条件为0/null,那么数据库将不返回任何内容,因为没有月/年==0或firstname/lastname==null;我想要的是,如果year/month/lastname/firstname为0/null,则忽略它并检查其他条件
有什么想法吗?您可以将逻辑添加到LINQ查询以检查条件
users = _context.Users.Where(x => x.Id !=0
&& x.FirstName != null
&& x.FirstName != null
&& x.Year != 0
&& x.Month != 0)
.ToList();
我想你应该像这样分别检查每种情况。
例如,当年份!=0且未设置其他每一个参数,则原始代码将不返回任何内容。尝试此
users=\u context.users.Where(x=>
&&(x.FirstName!=null | | x.FirstName==FirstName)
&&(x.Year==0 | | x.Year==Year)
&&(x.Month==0 | | x.Month==Month)
托利斯先生()
这将搜索所有不为空的数据,对吗?我想让它使用我给定的参数搜索数据库。为了更好地理解,我添加了上面的整个方法。因此,这段代码在数据库中执行简单搜索,其中year==createdAt.year&&month==createdAt.month。但是,如果其中一个条件为0,然后数据库将不返回任何内容,因为没有月/年==0;我想要的是,如果年/月为0,则忽略它并检查其他条件。这是一个非常好的提示,谢谢。但是,它需要一些修改以使其工作。我们应该检查月==0 | | x.month==month,而不是x.year!=0h是0,这将是真的,并且不会检查第二个,对吗?是的,我在两周前做了一个筛选器时遇到了相同的情况。告诉我们它是否有效:DI尝试过,在您的解决方案中,您检查过(x.year/month/firstname!=null/0),但是您没有检查参数year/month/firstname==0/null,那么year/month/firstname仍然可以是0并被传入。然后它仍然不起作用。ivooQ的答案起作用。请看他的第二个样式。第二个样式是正确的答案。第一个样式将给出一些关于简化三元表达式的警告。谢谢!
users = _context.Users.Where(x => x.Id !=0
&& x.FirstName != null
&& x.FirstName != null
&& x.Year != 0
&& x.Month != 0)
.ToList();
// 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));