asp.net-mvc-3 - 哪个是公开实体或 DTO 以在 mvc3 中查看的最佳实践?

我已经创建了我自己定制的大量架构,包括用于不同技术的 n 层。

目前正在使用 asp.net mvc 框架开发 n 层架构。问题是我在数据访问层有 Entity Framework 。由于实体将拥有所有它的关系元数据和导航属性,因此它变得更重。我觉得直接通过 mvc View 公开这些实体是不明智的。

我更喜欢公开自己定制的实体模型,而不是更轻量级的 mvc View 。

但这也导致我将数据从我的原始实体转换为自定义模型的开销。

例如,我有 Employee 实体,它是从 Entity Framework 的 edmx 文件生成的。它包含总共 20 个具有所有导航属性的字段。

现在在 mvc 中查看我只需要显示 2 个字段进行编辑。

那么我们是需要公开原始实体以查看还是需要创建这两个字段的 DTO/自定义模型然后公开该 View ?

最佳答案

我会使用 View 模型。我学会了不要将我的域对象暴露给 View ,我宁愿将我的域对象映射到 View 模型并将该 View 模型返回给 View 。

这是一个部分 View 模型,如果您需要更多员工数据来创建/编辑或显示,您可能有更多属性:

public class EmployeeViewModel
{
     public string FirstName { get; set; }
     public string LastName { get; set; }
}

在我的 Controller 的操作方法中,它看起来像这样:

public ActionResult Edit(int id)
{
     Employee employee = employeeRepository.GetById(id);

     // Mapping can be done here by using something like Auto Mapper, but I am
     // manually mapping it here for display purposes

     EmployeeViewModel viewModel = new EmployeeViewModel();
     viewModel.FirstName = employee.FirstName;
     viewModel.LastName = employee.LastName;

     return View(viewModel);
}

然后你的 View 可能看起来像这样:

<td>First Name:</td>
<td>@Html.TextBoxFor(x => x.FirstName, new { maxlength = "15" })
    @Html.ValidationMessageFor(x => x.FirstName)
</td>

我更喜欢有一个 View 模型,它只包含 View 所需的员工值。假设你的员工有 20 个属性,你只需要更新 2 个字段,为什么然后将所有 20 个传递给 View ? 只使用你需要的。

https://stackoverflow.com/questions/9819615/

相关文章:

.NET - WinDBG - 字符串的内容

ruby-on-rails-3 - 在 Rails 模型中一起验证日期和时间字段

android - 微调器依赖于 android 中的另一个微调器

css - 宽度为 100% 的额外一个像素

c# - 以编程方式检查 WSDL 文件支持的 SOAP 版本(1.1 或 1.2 或两者)

assembly - 与 NASM 打个近亲电话

post - 无法打开流 : HTTP request failed! HTTP/1.0 400 错

git - 如何从 git 存储库中完全删除数据?

google-chrome-extension - float popup.html div

ruby-on-rails - 从 Engine in Rails 3.x 应用程序重新打开模型和