我在ASP.NET MVC工作,我有一个场景,用户可以选择多个选项来获取医生列表,这就是我的动作的样子。
public JsonResult DoctorsList(int? specialization , int? city, int? area, int? insurance_company, string doctor_name )
这些参数中的任何一个都可以有一些值,并且它们中的任意数量都可以为null也可以为null,因为我将返回所有记录。 现在我知道了一个漫长而复杂的方法,我可以对这些参数进行不同的组合,并检查哪一个是空的,哪一个不是,然后根据它编写我的查询。 但是还有其他更短效的方式吗? 现在我正在使用OR条件来获取这样的记录
var doctors = db.Doctors.Where(e =>
e.specialization == specialization ||
e.Clinics.FirstOrDefault(cs => cs.doctor_id == e.doctor_id).Area.city_id == city ||
e.Clinics.FirstOrDefault(cs => cs.doctor_id == e.doctor_id).area_id == area ||
e.Clinics.FirstOrDefault(cs => cs.doctor_id == e.doctor_id).ClinicInsuranceCompanies
.Select(sin=>sin.company_id).ToList().Contains(insurance_company) ||
e.first_name == doctor_name ||
e.last_name == doctor_name
)
.Select(s => new
{
doctor_name = s.first_name + " " + s.last_name
}).ToList();
但是我希望它能够组合使用,例如选择具有specialization_id = 1和city_id = 2的医生,以及其他类似的组合。但如果只有一个条件匹配
答案 0 :(得分:0)
对于您的场景,我认为这种方法可能有效,而不是在其他条件下四处走动。我认为&&应该用来精确过滤,但你可以使用||算符,如果那就是你想要的,
var doctors = db.Doctors.Where(e =>
(specialization != null && e.specialization == specialization) &&
(city != null && e.Clinics.FirstOrDefault(cs => cs.doctor_id == e.doctor_id).Area.city_id == city) &&
(area != null && e.Clinics.FirstOrDefault(cs => cs.doctor_id == e.doctor_id).area_id == area) &&
(insurance_company != null && e.Clinics.FirstOrDefault(cs => cs.doctor_id == e.doctor_id).ClinicInsuranceCompanies
.Select(sin => sin.company_id).ToList().Contains(insurance_company)) &&
(doctor_name != "" && e.first_name == doctor_name || e.last_name == doctor_name)
)
.Select(s => new
{
doctor_name = s.first_name + " " + s.last_name
}).ToList();
答案 1 :(得分:0)
这就是我正在寻找的@ imanshu15回答给了我一个提示。
var doctors = db.Doctors.Where(e =>
(specialization != null && e.specialization == specialization) || (specialization == null)
).Where(e =>
(city != null && e.Clinics.FirstOrDefault(cs => cs.doctor_id == e.doctor_id).Area.city_id == city) || (city == null)
).Where(e =>
(area != null && e.Clinics.FirstOrDefault(cs => cs.doctor_id == e.doctor_id).area_id == area) || (area == null)
).Where(e =>
(insurance_company != null && e.Clinics.FirstOrDefault(cs => cs.doctor_id == e.doctor_id).ClinicInsuranceCompanies
.Select(sin => sin.company_id).ToList().Contains(insurance_company)) || (insurance_company == null)
).Where(e =>
(doctor_name != null && e.first_name == doctor_name) || (doctor_name == null)
)