【发布时间】:2013-10-17 19:30:47
【问题描述】:
我问了一个关于将 ViewModels 映射到控制器中的实体框架模型的最佳实践的问题,并被告知我的代码是正确的(使用 LINQ 投影),但也可以使用 AutoMapper。
现在我觉得我需要/想要将 Controller 方法中发生的大部分内容转移到新的 Service 层,这样我就可以在需要时在该层添加业务逻辑,然后在我的控制器中调用方法。但我不确定该怎么做。当然,我的 ViewModel 都将保留在 Web 项目中,那么我在服务层中的方法应该是什么样的?我应该在哪里/如何映射 ViewModel?
这是当前 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();
}
}
【问题讨论】:
-
存储库模式怎么样? stackoverflow.com/questions/11985736/…
-
你有一个
domain layer,它包含你的domain objects,还是你的models在表示层中的那个? -
PASSEntities 上下文引用了我来自实体框架的模型,这些模型包含在一个单独的项目中。我相信这是我的领域模型...?
标签: c# asp.net-mvc entity-framework