Joel Peltonen
Joel Peltonen

Reputation: 13402

Should I map my MVC3 Models and my Entity Framework Models and if; how?

I'm learning as I go, so I'm not familiar with all of the concepts behind EF and MVC3. I have an app where my EF Models === MVC3 Models, but I also have some aggregate ViewModels. I call things like Person dude = Person.Get(id); in Controllers, where Person is an EF model generated from a database, which I extend with my custom methods, such as dude.GetSiblings();

What I want to do now (if you don't tell me that this is a bad idea) is to move the EF code into another assembly, create yet another assembly with new simpler non-entity models that I can feed to my views and somehow (if possible) serialize and move around as JSON.

The problem is I don't know how. If I move my EF models to a different project (like a separate DAL), how would I create second models that map to Ef models? Wouldn't that cause a lot of repetition if I had code like int id {get;set;} string name {get;set} on both the EF model and the MVC3 model? In my ViewModels I simply use the entities directly like class ViewModelX { Person person; List<Post> posts; int something; } - but that is simply a packaged set of entities rather than a model, isn't it?

What about methods like GetSiblings? var list = dude.GetSiblings() in Controller and public List<Person> GetSiblings() { return this.EFPerson.GetSiblings(); } in MVC3 model? I'm getting very confused as to what goes where. When googling around, I really only found advanced and very beginner tutorials - or maybe I just don't know what to look for so I kindly ask for your assistance!

Upvotes: 1

Views: 180

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038720

If I move my EF models to a different project (like a separate DAL), how would I create second models that map to Ef models?

The view models reside inside the ASP.NET MVC application.

Wouldn't that cause a lot of repetition if I had code like int id {get;set;} string name {get;set} on both the EF model and the MVC3 model?

Yes, it will cause. That's what View Models are intended to do. To contain the data that the view needs to work with. Where does this data come from doesn't really matter. You could use tools such as AutoMapper to automate the mapping between your domain models and view models.

What about methods like GetSiblings? var list = dude.GetSiblings() in Controller and public List GetSiblings() { return this.EFPerson.GetSiblings(); } in MVC3 model?

Here's how a typical controller action might look like:

public ActionResult SomeAction(int id)
{
    // fetch an instance of the domain model:
    var domainModel = DomainLayer.GetSiblings(id);

    // map the domain model to a view model (using AutoMapper):
    var viewModel = Mapper.Map<DomainModel, ViewModel>(domainModel);

    // pass the view model back to the view
    return View(viewModel);
}

Upvotes: 1

Related Questions