Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Couple of things to know:</p> <h2>1. Unit of Work</h2> <p>Unit of Work is not necessarily some kind of implementation for <code>IUnitOfWork</code>. 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's <code>DbContext</code> <strong>is</strong> a kind of <code>Unit of Work</code> pattern. Your <code>IDbSet&lt;&gt;</code>s are your repositories. Don't try to abstract from your ORM, start with simplest possible thing.</p> <h2>2. DbContext injection</h2> <p>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 <code>DependencyResolver</code>. Your controller could be look like (example also contains AutoMapper usage example, see next point about ViewModels for that):</p> <pre><code>public CustomerController : Controller { public CustomerController(MyDbContext data, IMappingEngine mapper) { Data = data; Mapper = mapper; } public MyDbContext Data { get; set; } public IMappingEngine Mapper { get; set; } // Other controller code } </code></pre> <h2>3. View Models</h2> <p>This, again, is a pattern that is so easily implementable - just have your <code>CustomerViewModel</code> and use <a href="http://automapper.org" rel="nofollow">AutoMapper</a> to easily transform your <code>Customer</code> to <code>CustomerViewModel</code> so that you can do it like this:</p> <pre><code>public ActionResult Details(int id) { var customer = Data.Customers.FirstOrDefault(c =&gt; c.Id == id); if (customer == null) return new HttpNotFoundResult(); return View(Mapper.Map&lt;CustomerViewModel&gt;(customer)); } </code></pre> <p>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.</p> <p>Hope this helps!</p>
 

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