AxSc
AxSc

Reputation: 636

MVC 3 Code First ViewModel - How to?

I'm currently playing around with ASP .NET MVC 3 and - for data access - the code first approach of the Entity Framework.

I've read a lot of documentation, blogs, stackoverflow questions etc. but haven't found a precise answer to the following question and I hope someone out there can help me.

I have a simple (database) model containing two entites: Project and Customer

public class Project
{
    public int Id { get; set; }
    public string Name { get; set; }
    public virtual Customer Customer { get; set; }
}

and...

public class Customer
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int Rate { get; set; }
}

For displaying - for example - a list of the customers I have created a simple ViewModel:

public class ProjectListModel
{
    public List<Project> Projects { get; set; }
}

The code in my controller is:

public ActionResult ProjectList()
{
    var model = new ProjectListModel()
    {
        Projects = db.Projects.OrderBy(x => x.Customer.Id).ToList<Project>()
    };
    return PartialView("_ProjectList", model);
}

So I can display the list of the projects and even the corresponding customer name.

@Html.DisplayFor(modelItem => item.Name), @Html.DisplayFor(modelItem => item.Customer.Name))

And here starts my question ;-)

I'm unsure if I understood the concept of ViewModels correctly as I'm returning a list of my "database objects". How would you do that? I could imagine a new class:

public class SingleProjectForViewModel
{
  public string ProjectName {get;set;}
  public string CustomerName { get;set;}
}

and change my ViewModel to:

public class ProjectListModel
{
  public List<SingleProjectForViewModel> {get;set;}
}

...but then the code in my controller would become very long just to fill the ViewModel (fetch from DB, create instance of SingleProjectForViewModel and add this instance to an instantiated List) - for this example that would be OK but with bigger data classes and more complex views...!?

I also read about Auto-Mapper but I'm unsure if it's "right" to use this tool for that kind of "problem".

Thank you very much for reading this - and much more for answering or any advice! :-)

Upvotes: 2

Views: 1560

Answers (1)

Kyle Trauberman
Kyle Trauberman

Reputation: 25694

You understand View Models correctly. They are intended to remove the View layer from having ANY coupling to the data layer.

You could/should break your data access code into helper classes and methods, to remove the complexity from your controllers. These methods would query the data layer and return the view model.

I haven't used automapper, but it sounds like something that could definitely help here.

Upvotes: 2

Related Questions