Dynamic Or Clause Linq
You can build a predicate incrementally.
Func<Pantient, bool> predicate = p => false;
if (User.IsInRole("Administrator"))
{
var oldPredicate = predicate;
predicate = p => oldPredicate(p) || p.AdministratorID == UserID;
}
if (User.IsInRole("Counselor"))
{
var oldPredicate = predicate;
predicate = p => oldPredicate(p) || p.CounselorID == UserID;
}
var query = db.Patients.Where(predicate);
would this work?
var query = Patients.Where(
x => (User.IsInRole("Administrator") && x.AdministratorID == UserID)
|| (User.IsInRole("Counselor") && x.CounselorID == UserID)
|| (User.IsInRole("Physician") && x.PhysicianID == UserID)
);
Just in case anyone else is looking a different solution i found linqkit very usefull and easy to use. So in your example the solution would be something like this:
var predicate = PredicateBuilder.New<Patients>(true);
if (User.IsInRole("Administrator"))
{
predicate = predicate.Or(x => x.AdministratorID == UserID);
}
if (User.IsInRole("Counselor"))
{
predicate = predicate.Or(x => x.CounselorID == UserID);
}
if (User.IsInRole("Physician"))
{
predicate = predicate.Or(x => x.PhysicianID == UserID);
}
query = query.Where(predicate)