I’m totally stuck.
-
I’ve got two Controller: “Customer” and “Address”. Both have the fields CustomerRepository and AddressRepository.
-
There are two ViewModels: CustomerViewModel and AddressViewModel. They also have the fields CustomerRepository and AddressRepository. (And also a parameterless constructor since they are parameters within the edit and create methods)
-
The Repositories themselves have a DbContext object from my Entities.
Now I’m running into one problem after another. I think I should have only ONE DbContext to share with all of my classes (Repositories AND ViewModels). And I think UnitOfWork is the solution. But I have no clue how to use that.
I currently tried to create a DbContext within the controllers constructor and pass it to every single object requiring it. But even that doesn’t work.
If code is necessary, I will post it.
Couple of things to know:
1. Unit of Work
Unit of Work is not necessarily some kind of implementation for
IUnitOfWork. It is just a pattern that might be applied in many ways. First, and foremost – you should understand what is it for before actually using it and overcomplicate things around. Moreover, EF Code-First DbContext API’sDbContextis a kind ofUnit of Workpattern. YourIDbSet<>s are your repositories. Don’t try to abstract from your ORM, start with simplest possible thing.2. DbContext injection
For the beginning, just inject the DbContext to your Controller with constructor injection. Don’t forget to setup the IoC container of choice and wire up the MVC’s
DependencyResolver. Your controller could be look like (example also contains AutoMapper usage example, see next point about ViewModels for that):3. View Models
This, again, is a pattern that is so easily implementable – just have your
CustomerViewModeland use AutoMapper to easily transform yourCustomertoCustomerViewModelso that you can do it like this:You can interrogate the AutoMapper’s website on how to wire it up and make it running.
Notice that you don’t get the ViewModel from DbContext directly. You obtain an “entity” instead which then transformed to appropriate View Model.
Hope this helps!