c# - 当任何条件不为空时 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,那么只需忽略它并检查其他条件。
任何想法?
解决方案
// 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 且未设置所有其他参数时,您的原始代码将不返回任何内容。
推荐阅读
- c# - 如何使用 Xamarin.Forms 中的绑定启用多选列表视图的开关?
- java - 为我的 java 游戏渲染不同层中的对象的有效方法是什么
- c++ - 如何使用 Valgrind 确定“仍然可用”内存泄漏的来源?
- wpf - 我安装的 WPF 应用程序在尝试创建文件时崩溃
- android - RxJava 有条件地从 Single 中返回 Maybe
或 Maybe.empty() - windows - windows minikube kubectl 无法拉取镜像
- hadoop - 我必须创建 /tmp 和 /user/hive/warehouse 吗?
- java - Micronaut 是否应该为依赖注入错误生成编译器警告/错误?
- dialogflow-es - 在 Dialogflow 中验证用户输入
- javascript - 有没有办法判断您是否从服务人员那里获取缓存数据?