大佬教程收集整理的这篇文章主要介绍了c# – 将代码移动到服务层的最佳实践,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
现在我觉得我需要/想要将Controller方法中发生的大部分内容移动到新的service层,这样我就可以在需要时在此层添加业务逻辑,然后在我的控制器中进行方法调用.但我不确定该怎么做.我的viewmodel当然都会保留在Web项目中,那么我的服务层中的方法应该是什么样子以及我在哪里/如何映射viewmodel?@H_607_7@
以下是当前GET和POST控制器方法的示例:@H_607_7@
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(); } }
public ActionResult Laboratories() { // Get the laboratories domain models from the service layer. var laboratories = _laboratoryservice.GetLaboratories(); // Map the domain models to view models using AutoMapper. var laboratoriesModel = Mapper.Map<List<Laboratoryviewmodel>>(laboratories); // Return view model to the view. return View(laboratoriesModel); }
使用此方法,您需要一个核心/域层,您的域实体可以在其中存在.服务层包含业务逻辑并与域模型交互(例如通过存储库)并将实体化对象返回给控制器.正如您所建议的那样,您的视图模型应该确实位于网站项目中.@H_607_7@
另请查看this question,其中我提供了类似解决方案的示例.@H_607_7@
更新@H_607_7@
服务层中的GetLaborarties方法返回(模型)域模型的集合:@H_607_7@
public List<Laboratory> GetLaboratories() { return _db.Laboratories.ToList(); }
现在,在控制器中调用此方法并将其映射到视图模型.您可以使用Linq SELEct方法执行此操作:@H_607_7@
public ActionResult Laboratories() { // Get the laboratories domain models from the service layer. var laboratories = _laboratoryservice.GetLaboratories(); var laboratoriesModel = laboratories.SELEct(new Laboratoryviewmodel { // Map here.. }).ToList(); return View(laboratoriesModel); }
或者如上所述使用AutoMapper.@H_607_7@
更新2@H_607_7@
假设我们有这个域模型:@H_607_7@
public class Category { public String Name { get; set; } public String UrlName { get; set; } // Other properties.. public virtual ICollection<Product> Products { get; set; } }
public Categoryservice : ICategoryservice { public Category GetByName(String Name) { return _categoryRepository.Table .Include(c => c.Products) // Include related products .FirstOrDefault(c => c.UrlName = Name); } }
我配置了实体框架,类别包含零个或多个产品.使用Include方法,我要求Entity Framework在SQL查询中包含相关产品.现在产品将包含该类别的所有相关产品.@H_607_7@
以上是大佬教程为你收集整理的c# – 将代码移动到服务层的最佳实践全部内容,希望文章能够帮你解决c# – 将代码移动到服务层的最佳实践所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。