gpt4 book ai didi

c# - 我们如何使用 EF 在 ASP.Net MVC 应用程序中创建 3 层架构?

转载 作者:行者123 更新时间:2023-11-30 14:28:45 25 4
gpt4 key购买 nike

我正在使用 Entity Framework 6 在 ASP.NET MVC 5 中创建一个新项目(Web 应用程序)。我曾使用 ASP.Net Web 表单应用程序在 3 层架构中工作,但我对处理 Entity Framework 、模型等感到困惑.那么,我如何使用 EF 在 MVC 中构建 3 层架构并且与 Entity Framework 一起使用是可行的?

最佳答案

是的,您可以实现 3/N 层架构(或类似架构)。

ASP.NET MVC 与 Entity Framework 有很好的协作。 EF 甚至在默认 ASP.NET MVC 模板中安装并用于用户/角色管理(身份)。

典型的 ASP.NET MVC 应用程序由模型、 View 和 Controller 组成。简而言之:

  • 模型是 POCO。模型封装数据并负责数据有效性。打个比方——这是应用层的一部分和数据层的一部分。数据层还包括 EF 数据库上下文类。
  • View 是生成 html 的 .cshtml 文件并且可以是强类型的(有模型)。打个比方 - 这是表示层。
  • Controller 负责处理 HTTP 请求、检索数据模型并将模型传递给 View 。打个比方——这是应用层(业务逻辑)的一部分。

通常, Controller 会接收一些 viewModel,对其进行验证、处理并返回一些操作结果( View 、部分 View 、JSON、文件等)。在流程部分 Controller 可以初始化 Entity Framework 上下文,通过EF db上下文等获取或保存数据到数据库。

“让 Controller 尽可能薄”几乎总是一个好主意,因此许多 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.
}

Controller

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 模型

// 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 -->

关于c# - 我们如何使用 EF 在 ASP.Net MVC 应用程序中创建 3 层架构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28431421/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com