Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC: Controller knows about persistence?

Just getting started with MVC, long-time WebForms experience.

I don't want to decorate my entities with UI-oriented properties like "display name" or "required", plus a lot of them have more methods and properties than I care to expose on a view.

So I'm experimenting with ViewModels that wrap, or in other ways interact with the actual entities in my system. What I don't like is how the Controller has to know to query a repository and then instantiate a ViewModel to wrap the entity it got back.

What are best-practices for a controller to interact with ViewModels without having to know how they're persisted? All the examples I see talk directly to EntityFramework or other ORM's.

I was thinking about static methods on the ViewModel classes that take an IRepository reference and an ID to load and return the ViewModel. Does that make sense?

like image 682
n8wrl Avatar asked Jul 19 '26 23:07

n8wrl


1 Answers

Use DependencyInjection to pass your Repository to your controller.

public HomeController
{
    private readonly IHomeRepository repo;

    public HomeController(IHomeRepository repository)
    {
        repo = repository;
    }
}

Then inside your action methods, get the items, and create your ViewModels from those objects.

public ActionResult Index()
{
    // IEnumerable models are bad, but this is just a quick demo.
    var viewModels = repo.GetWidgets().Select(w => new WidgetModel(w));

    return View("Index", viewModels);
}
like image 176
krillgar Avatar answered Jul 21 '26 15:07

krillgar