问题描述
我有医院和医疗专科医生。
I have Hospitals and Medical Specialities.
我的医疗专业页面以医院ID方式退回数据:
My Medical Specialities page return data by hospital ID in this way:
localhost / MedicalSpecialities / 1,1是HospitalID。如果我手动更改链接,我可以访问任何医院信息。
localhost/MedicalSpecialities/1, 1 is the HospitalID. if I change manually the link I can access any hospital info.
我有这样用户与医院联系:
I have users associated to hospitals in this way:
我需要查询用户已经关联的医院ID,并检查当前的HospitalID是否在列表中。
I need to query the Hospital ID's that user have associated AND check if the current HospitalID is on the list.
返回用户连接的所有医院:
This return all hospitals that user have connected:
var userID = User.Identity.GetUserId();
var result = db.Hospitals.Include("UserHospitals")
.Where(x => x.UserHospitals
.Any(u => u.Id == userID))
.ToList();
推荐答案
您可以基本更新 Any()
方法包括对HospitalId列的检查。
You can basically update the condition in your Any()
method to include a check against the HospitalId column.
var hospitalId =5;
var result = db.Hospitals
.Include(y=>y.UserHospitals)
.Where(x => x.UserHospitals.Any(u => u.Id == userID
&& u.HospitalID==hospitalId ))
.ToList();
如果您期望只有一家医院为此条件,您还可以考虑使用 FirstOrDefault()
方法。
If you are expecting only a single hospital for this condition, you may also consider using FirstOrDefault()
method.
var singleHospital = db.Hospitals
.Include(y=>y.UserHospitals)
.Where(x => x.UserHospitals.Any(u => u.Id == userID
&& u.HospitalID==hospitalId ))
.FirstOrDefault();
if(singleHospital!=null)
{
//Safely use it.
}
这篇关于通过查询结果阻止访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!