是的,您可以实现 3/N 层架构(或类似的架构)。
ASP.NET MVC 与实体框架有很好的合作。 EF 甚至在默认的 ASP.NET MVC 模板中安装并用于用户/角色管理(身份)。
典型的 ASP.NET MVC 应用程序由模型、视图和控制器组成。简要说明:
- 模型是 POCO。模型封装数据并负责数据有效性。打个比方——这是应用层的一部分,也是数据层的一部分。数据层还包括 EF db 上下文类。
- 视图是 .cshtml 文件,可以生成 html 并且可以进行强类型化(具有模型)。类比 - 这是表示层。
- 控制器负责处理 HTTP 请求、检索数据模型并将模型传递给视图。打个比方 - 这是应用层(业务逻辑)的一部分。
通常,控制器将接收一些 viewModel,对其进行验证、处理并返回一些操作结果(视图、部分视图、JSON、文件等)。在流程部分,控制器可以初始化实体框架上下文,并通过EF db上下文等获取或保存数据到数据库。
“使控制器尽可能精简”几乎总是一个好主意,因此许多 ASP.NET MVC 解决方案使用存储库/工作单元或服务模式。
使用服务创建某些实体的 MVC 应用程序的一些典型部分的示例:
服务
// Connect to database through entity framework db context.
public interface IMyService
{
MyDbContext DbContext { get; set; }
IQueryable<Something> GetSomething( ... query params ... );
void CreateSomething(Something model);
// etc.
}
控制器
public MyController
{
private IMyService myService;
public MyController(IMyService myService)
{
this.myService = myService;
}
// Showing create/edit form
[HttpGet]
public ActionResult CreateSomething()
{
// Create Empty view model. new SomeViewModel(); for example.
// Get some nomenclatures for dropdowns etc. through the service (if needed).
// return View(viewModel);
}
// Processing the post request
[HttpPost]
public ActionResult CreateSomething(SomeViewModel viewModel)
{
// Check validity of viewModel (ModelState.IsValid)
// If not valid return View(viewModel) for showing validation errors
// If valid map the viewModel to Model (through AutoMapper or custom mapping)
// Call myService CreateSomething method.
// Redirect to page with details.
}
}
型号
public class Something
{
public int Id { get; set; }
public string Name { get; set; }
// .. more properties (can be decorated with validation attributes)
}
演示视图模型
// View model for Something class. Including only properties related to the current UI.
public class SomeViewModel
{
public int Id { get; set; }
// .. more properties (can be decorated with validation attributes)
}
查看
@model SomeViewModel
<!-- Form -->
@Html.ValidationForModel()
@Html.EditorForModel()
submit button
<!-- /Form -->