title: Loading Related Entities in Mocked DbContext using Moq for Web Api 2 Controller Tests
body: <p>I'm trying to unit test some Web Api 2 Controllers that use Entity Framework 6 but having issues with the loading of the related entities after the entity has been added. I'm using Moq to create a mocked DbContext and DbSet, and have added </p>
  
  <pre><code>public virtual void MarkAsModified&lt;T&gt;(T item) where T : class
  {
     Entry(item).State = EntityState.Modified;
  }
  </code></pre>
  
  <p>to get around the <code>_db.Entry(foo).State = EntityState.Modified;</code> issue on a Put action.</p>
  
  <p>The Api Action is a Post in this simplified example where we need to get back 2 related entities (Bar and Qux).</p>
  
  <pre><code>[ResponseType(typeof (Foo))]
  public async Task&lt;IHttpActionResult&gt; PostFoo(Foo foo)
  {
    if (!ModelState.IsValid)
    {
       return BadRequest(ModelState);
    }
    //Do other stuff
    _db.Foos.Add(foo);
    _db.Entry(foo).Reference(x =&gt; x.Bar).Load();
    _db.Entry(foo).Reference(x =&gt; x.Qux).Load();
    await _db.SaveChangesAsync();
    return CreatedAtRoute("DefaultApi", new {id = foo.Id},foo);
  }
  </code></pre>
  
  <p>And then a simplified test would be</p>
  
  <pre><code>[TestMethod]
  public async Task PostFoo()
  {
    var model = new Foo
    {
      Name="New Foo",
      QuxId = 99,
      Qux = null,
      BarId = 66,
      Bar = null
    };
   var result = await _controller.PostFoo(model) as CreatedAtRouteNegotiatedContentResult&lt;Foo&gt;;
   Assert.IsNotNull(result);
   Assert.IsNotNull(result.Qux);
   Assert.IsNotNull(result.Bar);
  }
  </code></pre>
  
  <p>Is there a more mock-friendly way of doing <code>_db.Entry(foo).Reference(x =&gt; x.Bar).Load();</code></p>