我之前提出了一个关于如何将ViewModels映射到Entity Framework models的最佳实践问题,并被建议使用LINQ投影(Projection)来编写代码,虽然AutoMapper也可以用作补充。
现在我感觉需要/想要将控制器方法中大部分操作移到新的服务层(Service layer),这样我就可以在需要时在该层添加业务逻辑,然后只需在我的控制器中调用方法即可。但是我不确定该怎么做。我的ViewModels当然仍然在Web项目中,那么服务层中的方法应该长什么样子,我应该在哪里/如何映射这些ViewModels?
以下是当前GET和POST控制器方法示例:
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();
}
}