asp.net-mvc-3 – 如何在ASP.NET MVC 3中分离代码(清除代码分离)
我现在只想知道如何使用EF在MVC3中以正确的方式分离代码
根据我的项目结构. 演示 – >查看&调节器 域名 – >模型(商业实体) 数据 – > RepositoryBase,IRepository,ApplicationDbContext 服务 – >第三方服务(PayPal,SMS)或应用服务 ApplicationDbContext需要Model作为参考. public sealed class ApplicationDbContext : DbContext { public DbSet<CountryModel> Country { get; set; } protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Conventions.Remove<PluralizingTableNameConvention>(); } } 1.将DbContext放入数据是否合适?或者我必须将其移至域名? 现在在Controller中我必须编写代码 using (ApplicationDbContext db = new ApplicationDbContext()) { var countryRepository = new Repository<Country>(db); if (ModelState.IsValid) { countryRepository.insert(country); db.SaveChanges(); } } 有没有办法分离这个代码块任何业务层/服务层? 所以我们只是从控制器和放大器调用该层.只需通过特定业务实体即可执行其余操作. 我想做PL – > BLL – > DLL方法使用MVC 3& EF? 请建议我正确的方法. 解决方法
是的,这是它所属的地方.
不,你绝对不应该在控制器中编写这样的代码,因为你现在正在使你的控制器与你正在使用的特定数据访问技术紧密耦合(在你的情况下是EF).更糟糕的是,您无法单独对控制器进行单元测试. 我建议你在界面中的实体上抽象操作(你已经在你的问题中提到了它 – IRepository).现在您的控制器可以将存储库作为依赖: public class CountriesController: Controller { private readonly IRepository repository; public CountriesController(IRepository repository) { this.repository = repository; } public ActionResult Index(int id) { Country country = this.repository.Get<Country>(id); return View(country); } [HttpPost] public ActionResult Index(Country country) { if (ModelState.IsValid) { this.repository.Insert(country); return RedirectToAction("Success"); } return View(country); } } 现在,您所要做的就是配置您喜欢的依赖注入框架,以将此IRepository的特定实现注入控制器构造函数.在您的情况下,这个特定的实现可能是一些实现IRepository接口的类,并且正在使用ApplicationDbContext. 这样,您就可以从控制器中抽象出数据访问逻辑. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
- asp.net – EF首先使用代码与一对多关系创建重复的外键
- asp.net-mvc – 如何使用枚举值填充下拉列表?
- asp.net – AsyncFileUpload控件
- asp.net – 你能以编程方式设置MachineKey吗?
- asp.net – 具有html5中的文本以外的输入类型的UpdatePanel
- asp.net – 跨线程使用HTTPContext
- asp.net-mvc – 在MVC3中的错误 – 请求永远不会超时 在同一
- asp.net – 正则表达式匹配10-14位数
- 有没有带语音记录示例代码的ASP.NET?
- asp.net-mvc-2 – 如何在局部视图中获取与父操作关联的Rout
- asp.net-web-api – 使用OAuth和单页应用程序实现
- asp.net-core – 是否可以直接在Azure WebApps中
- asp-classic – 为ServerXMLHTTP请求设置超时
- ASP.NET Core的JWT的实现(自定义策略形式验证)
- asp.net – 什么时候回输HTML输入标签?
- 实现ASP.NET多文件上传程序代码
- asp.net-mvc – ASP.Net MVC尝试抓住最佳实践
- asp.net-mvc – jQGrid和MVC 3.0 ViewModel
- asp.net-mvc-3 – 为什么_ViewStart.cshtml访问V
- asp.net – ASP .NET核心Cookie身份验证到期时返