I asked a previous question regarding best practices for mapping ViewModels to Entity Framework models in my controllers and was advised that my code was correct (using LINQ projection), though AutoMapper could be used in addition.
Now I feel like I need/want to move the bulk of what happens in the Controller methods to a new Service layer so I can add business logic when needed at this layer and then just have method calls in my controllers. But I am not exactly sure what to do. My ViewModels would all remain in the web project of course so what should my methods in the service layer look like and where/how do I map the ViewModels?
Here is a sample of a current GET and POST controller method:
public ActionResult Laboratories()
{
var context = new PASSEntities();
var model = (from a in context.Laboratories
select new LaboratoryViewModel()
{
ID = a.ID,
Description = a.Description,
LabAdmins = (from b in context.Users_Roles
join c in context.Users on b.User_ID equals c.ID
where b.Laboratory_ID == a.ID
select new LabAdminViewModel()
{
ID = b.ID,
User_ID = b.User_ID,
Role_ID = b.Role_ID,
Laboratory_ID = b.Laboratory_ID,
BNL_ID = c.BNL_ID,
First_Name = c.Pool.First_Name,
Last_Name = c.Pool.Last_Name,
Account = c.Account
})
});
return View(model);
}
[HttpPost]
public ActionResult AddLaboratory(LaboratoryViewModel model)
{
try
{
using (PASSEntities context = new PASSEntities())
{
var laboratory = new Laboratory()
{
ID = model.ID,
Description = model.Description
};
context.Laboratories.Add(laboratory);
context.SaveChanges();
}
return RedirectToAction("Laboratories");
}
catch
{
return View();
}
}