Reputation: 9818
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
Reputation: 4443
Viewmodel is best solution.
General approach get entities in controller and use some mapper library(I recommend emit mapper) to map entity to your viewmodel
Upvotes: 4