Gillardo
Gillardo

Reputation: 9818

.Net MVC Entities and ViewModels...Same or Separate?

I am new to asp.net MVC and i have created a project using Entity Framework code first approach. I have put my POCO objects in to a separate class library called Entities.

Now i would like to get some data from my service class, which returns an Entity and output that to the View. here is some very basic code

// in POCO library
public class MyEntity() {
    public int Id { get; set; }
    public String Name { get; set; }
}

// in service library
public class EntityService() {
    public MyEntity Get(int id) {
        return new MyEntity() { Id=1, Name="This is my entity name" };
    }
}

// controller in asp.net MVC web application
public MyController() : Controller
{
    private EntityService _service;

    public MyController(EntityService service) {
        _service = service;        
    }

    public ActionResult Index()
    {
        MyEntity entity = _service.Get(1);
        return View(entity);
    }
}

Now should i push MyEntity to the View, or should i be creating a separate ViewModel? Part of me thinks that creating a separate ViewModel would be best as to keep the separation between the Entities and my View, and also the "logic" to copy the fields i need would be in the controller. But another part of me thinks that creating a ViewModel is just going to be a near copy of the Entities so seems like a waste of time?

I would like to do it correctly, so thought i would ask here. Thanks in advance

Upvotes: 2

Views: 1050

Answers (1)

vborutenko
vborutenko

Reputation: 4443

Viewmodel is best solution.

  1. You can put attributes(validations and other)
  2. Your viewmodel can contain data from several data entities
  3. As you say you get separation between the Entities and View

General approach get entities in controller and use some mapper library(I recommend emit mapper) to map entity to your viewmodel

Upvotes: 4

Related Questions