Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I've felt the same discomfort. My only way around it has been to do the following:</p> <ol> <li>Create a binder to bind and validate the view model</li> <li>Create a binder to get the entity from the database (or just do this in the controller)</li> <li>Call an inherited Save method in the superclass. This method takes the viewmodel and the entity that will be updated, and does all the work you listed in your steps. </li> </ol> <p>The action method looks like this:</p> <pre><code>public ActionResult Whatever(TViewModel viewModel, TEntity entity) { return Save(viewModel, entity); } </code></pre> <p>The base controller has a generic definition, like so:</p> <pre><code>public abstract BaseController&lt;TEntity, TViewModel&gt; where TEntity : Entity where TViewModel : ViewModel </code></pre> <p>The constructor has two dependencies, one for the entity repository and another for the model mapper, like so:</p> <pre><code>protected BaseController(IRepository&lt;TEntity&gt; repository, IMapper&lt;TEntity, TViewModel&gt; mapper) </code></pre> <p>With this in place, you can then write a protected Save method that can be called from the controller actions in the subclass, like so:</p> <pre><code>protected ActionResult Save(TViewModel viewModel, TEntity entity) { if (!ModelState.IsValid) return View(viewModel); _mapper.Map(viewModel, entity); if (!entity.IsValid) { // add errors to model state return View(viewModel); } try { _repository.Save(entity); // either redirect with static url or add virtual method for defining redirect in subclass. } catch (Exception) { // do something here with the exception return View(viewModel); } } </code></pre> <p>As far as testability, you can test the save method passing in valid/invalid view models and entities. You can test the implementation of the model mapper, the valid state of the view model, and the valid state of the entity separately.</p> <p>By making the base controller generic, you can repeat this pattern for each entity/viewmodel combo in your domain, if you're creating many controllers to do the same thing.</p> <p>I'm very interested to hear what others have to say about this. Great question.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload