title: MVC 5 - Multiple DbContexts in a controller
body: <p>I am developing a MVC 5 internet application and I have a question in relation to having more than one <code>DbContext</code> class in a <code>controller</code>.</p>
  
  <p>My <code>DbContext</code> class has many <code>DbSet</code> objects for different model entities. None of my model entities are using virtual objects, however, my view models are using virtual objects in each controller.</p>
  
  <p>When a controller references different <code>DbSet</code> objects in the same controller/action result, should I use a different <code>DbContext</code> instance for each different <code>DbSet</code> reference? I have encountered the following error in a web service class when I try to access different <code>DbSets</code> to create a view model when using only one <code>DbContext</code> instance: </p>
  
  <blockquote>
    <p>Message = "There is already an open DataReader associated with this
    Command which must be closed first."</p>
  </blockquote>
  
  <p>Can this happen when doing CRUD operations on an object in a MVC controller when different <code>DbSets</code> are accessed using the same <code>DbContext</code> class?  </p>
  
  <p>Here is an example:</p>
  
  <p>I have a <code>MapLocationList</code> controller, that when creating/editing a <code>MapLocationList</code> object, the following different <code>DbSet</code> objects are accessed: <code>Asset</code>, <code>MapLocation</code>.</p>
  
  <p>How much increase in overhead is there when using more than one <code>DbContext</code> instance in a MVC controller?</p>
  
  <p>Basically, my question is should a different <code>DbContext</code> instance be used when accessing different <code>DbSets</code> in a controller/action result?</p>
  
  <p>Thanks in advance.</p>