简体   繁体   English

按查询结果阻止访问

[英]block access by query result

I have Hospitals and Medical Specialities.我有医院和医学专科。

My Medical Specialities page return data by hospital ID in this way:我的医学专科页面以这种方式按医院 ID 返回数据:

localhost/MedicalSpecialities/1, 1 is the HospitalID. localhost/MedicalSpecialities/1, 1 是 HospitalID。 if I change manually the link I can access any hospital info.如果我手动更改链接,我可以访问任何医院信息。

I have users associated to hospitals in this way:我有用户以这种方式与医院相关联: 在此处输入图片说明

I need to query the Hospital ID's that user have associated AND check if the current HospitalID is on the list.我需要查询用户关联的医院 ID,并检查当前的 HospitalID 是否在列表中。

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();

You can basically update the condition in your Any() method to include a check against the HospitalId column.您基本上可以更新Any()方法中的条件以包含对 HospitalId 列的检查。

var hospitalId =5;
var result = db.Hospitals
               .Include(y=>y.UserHospitals)
               .Where(x => x.UserHospitals.Any(u => u.Id == userID 
                                                 && u.HospitalID==hospitalId ))
               .ToList();

If you are expecting only a single hospital for this condition, you may also consider using FirstOrDefault() method.如果您只期望一家医院出现这种情况,您也可以考虑使用FirstOrDefault()方法。

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.
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM