Parameterize database column names in controller action
I want a controller action "ProfessorStatus" which queries "Professor" table and returns list of active professors for a particular school.
Here is the controller action I have, I am struggling with parameterizing the "School" columns
public ActionResult ProfessorStatus(string schoolType)
{
var activeProfessors = (from p in prof.ProfessorTable.Where(a => a.Engineering.Value == true)
group p by p.ProfessorID into g
select g.Key).ToList();
return View(activeProfessors);
}
Now, In the above controller action. Instead of hard coding "Engineering" I wa开发者_StackOverflow社区nt to parameterize it with "schoolType".
So if I pass schoolType = Medicine Then the controller will display professors from medicine school and so on for other school types.
How can I avoid hardcording here? Thanks in advance.
Your database is poorly designed.
Instead of having a boolean column for each school, you should have a separate table mapping professors to schools, with columns for professor ID and school name or ID.
You can then write
prof.ProfessorTable.Where(p => p.Schools.Any(ps => ps.School = schoolType))
If you really only need the professor ID, you could also write
prof.ProfessorSchools.Where(ps => ps.School = schoolType)
.Select(ps => ps.ProfessorId)
If you are not in a position to redesign your whole database and the systems that use it, you can still get around this by using expressions.
public ActionResult ProfessorStatus(string schoolType) {
Expresison<Func<Professor, bool>> filter;
switch (schoolType) {
case "Engineering":
filter= a => a.Engineering.Value == true;
break;
default:
throw new Exception("Unknown SchoolType - " + schoolType);
}
var activeProfessors = (from p in prof.ProfessorTable.Where(filter)
group p by p.ProfessorID into g
select g.Key).ToList();
return View(activeProfessors);
}
精彩评论