2

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

Gillardo
  • 9,518
  • 18
  • 73
  • 141
  • 1
    Create a separate view model. It won't be long before the mapping is not one-to-one. Also bear in mind that if you bind directly to entities, any user can alter any property just by submitting the right POST value. – Ant P Oct 02 '14 at 08:52
  • 1
    [This SO answer](http://stackoverflow.com/questions/11064316/what-is-viewmodel-in-mvc) gives some good reasons why a view model is a good approach. Also [this](http://geekswithblogs.net/michelotti/archive/2009/10/25/asp.net-mvc-view-model-patterns.aspx) and [this](http://www.mikesdotnetting.com/Article/188/View-Model-Design-And-Use-In-Razor-Views) –  Oct 02 '14 at 08:52

1 Answers1

4

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

vborutenko
  • 4,323
  • 5
  • 28
  • 48