title: "An entity object cannot be referenced by multiple instances of IEntityChangeTracker" with a custom model binder
body: <p>I've been following Darin's <a href="https://stackoverflow.com/a/8964723/729541">answer</a> to a question I had on slimming down my controllers and I'm running into problems with this <code>IEntityChangeTracker</code> exception:</p>
  
  <blockquote>
    <p>An entity object cannot be referenced by multiple instances of IEntityChangeTracker.</p>
  </blockquote>
  
  <p>Here's my model binder:</p>
  
  <pre><code>public class PostModelBinder : IModelBinder
  {
      private readonly IPostRepository _repository;
  
      public PostModelBinder(IPostRepository repository)
      {
          _repository = repository;
      }
  
      public object BindModel(ControllerContext controllerContext,
                              ModelBindingContext bindingContext)
      {
          var postIDValue = controllerContext.Controller.ValueProvider.GetValue("postID");
          int postID;
  
          if (postIDValue == null || !int.TryParse(postIDValue.AttemptedValue, out postID))
              return null;
  
          return _repository.FindPost(postID, filterByPublished: true);
      }
  }
  </code></pre>
  
  <p>After this, my custom action filter simply carries out a bit of validation on the post and redirects if the post isn't valid.  Up until this point, everything is fine.  The error happens in my controller when I try to update the post read count:</p>
  
  <pre><code>public class PostsController : Controller
  {
      private IPostRepository postRepository;
  
      // snip...
  
      [AutoMap(typeof(Post), typeof(PostViewModel)), HttpGet]
      [PostActionFilter]
      public ActionResult ShowPost(Post model)
      {
          postRepository.PostVisited(model);
  
          return View(model);
      }
  }
  </code></pre>
  
  <p>I understand <code>IEntityChangeTracker</code>'s complaining  because I effectively end up with 2 repositories referencing the same object and that just seems like bad mojo waiting to happen.  I know I could push the <code>PostVisited()</code> call into <code>PostModelBinder</code> but updating a model doesn't seem like behaviour that belongs there.</p>
  
  <p>Is there another way around this?</p>
  
  <p>Thank you.</p>