title: Automatically pass Entity to Controller Action
body: <p>When adding a controller for a model, the generated actions will look something like this</p>
  
  <pre><code>public ActionResult Edit(int id = 0)
  {
      Entity entity = db.Entities.Find(id);
      if (entity == null)
      {
          return HttpNotFound();
      }
      return View(entity);
  }
  </code></pre>
  
  <p>Now in my case I take a <strong>string id which can map to DB IDs in several ways</strong>, producing several lines of code for retrieval of the correct entity. Copy&amp;pasting that code to every action which takes an id to retrieve an entity feels very inelegant. </p>
  
  <p>Putting the retrieval code in a private function of the controller reduces the amount of duplicate code but I'm still left with this:</p>
  
  <pre><code>var entity = GetEntityById(id);
  if (entity == null)
      return HttpNotFound();
  </code></pre>
  
  <p>Is there a way to perform the lookup in an attribute and pass the entity to the action? Coming from python, this could easily be achieved with a decorator. I managed to do something similar for WCF services by implementing an <code>IOperationBehavior</code> which still does not feel as straight-forward. Since retrieving an entity by id is something you frequently need to do I'd expect there to be a way other than copy&amp;pasting code around.</p>
  
  <p>Ideally it would look something like this:</p>
  
  <pre><code>[EntityLookup(id =&gt; db.Entities.Find(id))]
  public ActionResult Edit(Entity entity)
  {
      return View(entity);
  }
  </code></pre>
  
  <p>where <code>EntityLookup</code> takes an arbitrary function mapping <code>string id</code> to <code>Entity</code> and either returns <code>HttpNotFound</code> or calls the action with the retrieved entity as the parameter.</p>