which is the best practices for exposing entity or DTO to view in mvc3?

怎甘沉沦 提交于 2019-12-12 20:26:42

问题


I have created my own customized lots of architecture including n-tier layers for different different technology.

Currently working on n-tier architecture with asp.net mvc framework. The problem is I have entity framework at data access layer. As the entities will have all it's relational metadata and navigation properties, it becomes heavier one. I am feeling like it is not wise to expose this entities directly over mvc view.

I am more favor in exposing own customized model of entities over mvc view which one be lighter one.

But this also leads me overhead of converting data from my original entities to customized model.

For example I have Employee entity which is as generated from edmx file of entity framework. It contains total 20 fields with all navigation properties.

Now over view in mvc I need to show only 2 fields for edit.

So do we need to expose original entity to view or need to create DTO/customized model of that two field and than expose that view?


回答1:


I would use a view model. I have learnt not to expose my domain objects to the view, I rather map my domain object to the view model and return this view model to the view.

Here is a partial view model, you might have more properties if you need more employee data to create/edit or display:

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

In my action method of my controller it would look something like this:

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);
}

And then your view might look something like this:

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

I prefer to have a view model that has only the values of employee that is needed on the view. Let say your employee has 20 properties, and you only need to update 2 fields, why then pass all 20 to the view? Use only what you need.




回答2:


You can expose original entity, that is nothing bad. But as soon as you need some other information on the view e.g. instead of Name and Lastname you need FullName, then you should create an EmployeeViewModel with only needed properties. You initialize it with desired values in an action and then pass it to the view.



来源:https://stackoverflow.com/questions/9819615/which-is-the-best-practices-for-exposing-entity-or-dto-to-view-in-mvc3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!