I have an application using c# and MVC5, with RazorEngine.
My application manages requests (orders from clients) and I need to show them in tables. To achieve this I have a Controller (HistoryController), a View (Index) and a Model (MaterialRequestModel) which takes several parameters in the constructor:
public MaterialRequestModel(MaterialRequest order, Employee aConcernedEmployee, Employee anOrderedbyEmployee, Office anOffice)
In my controller, HistoryController
I have the followin Index method, which gets all requests completed or canceled:
public ActionResult Index()
{
IQueryable<MaterialRequest> query= DB.MaterialRequest
.Where(m => m.MaterialStatusId == MatStatus.A9Cancelled || m.MaterialStatusId == MatStatus.A8Complete);
List<MaterialRequestModel> model= new List<MaterialRequestModel>();
foreach (MaterialRequest req in query)
{
model.Add(new MaterialRequestModel(req, DB.Employees.Find(req.ConcernedEmployeeId), DB.Employees.Find(req.OrderedByEmployeeId), DB.Offices.Find(req.OfficeId)));
}
return View(model);
}
Now, I could simply pass the query
to the the View, but that is not a good practice and the community (this one!) strongly suggests I use Models to avoid placing logic into the view.
However, I can't help to think that the way I am building my model
sucks terribly bad, because I am iterating over a large set of results.
How can I improve this code and make it decent without the loop?
Additionally, should I pass everything as a parameter to my model, or should I just pass the DB
object into the Models contructor and have it do the quereies there?