title: Entity Framework 6 exception: "The context cannot be used while the model is being created"
body: <p>I'm a bit new when it is coming to Entity Framework 6 from the old style of ADO.NET, so bear with me here.</p>
  
  <p>I'm trying to create a new WPF MVVM project and also a few WinForms that will use just straight out <code>DBContext</code> without data-binding with the EF 6.</p>
  
  <p>Using Visual Studio 2013 Entity framework wizard, I created a code-first by reverse engineer a current database on our business server. I then separated the data model classes from the context</p>
  
  <p>This is the <code>DbContext</code> code:</p>
  
  <pre><code>namespace EFModels
  {
      public partial class MyDataContext : DbContext
      {
          public MyDataContext () : base("name=MyDataContext")
          {
          }
  
          public virtual DbSet&lt;Calibration&gt; Calibrations { get; set; }
          public virtual DbSet&lt;OrderDetail&gt; OrderDetails { get; set; }
          public virtual DbSet&lt;OrderHistory&gt; OrderHistories { get; set; } 
          public virtual DbSet&lt;WorkDetail&gt; WorkDetails { get; set; }
  
          protected override void OnModelCreating(DbModelBuilder modelBuilder)
          {   
              modelBuilder.Entity&lt;WorkDetail&gt;()
                      .HasMany(e =&gt; e.Calibrations)
                      .WithOptional(e =&gt; e.WorkDetail)
                      .HasForeignKey(e =&gt; e.WorkID);  
          }
      }
  }
  </code></pre>
  
  <p>I've separated the data classes in a separate namespace, for example:</p>
  
  <pre><code>namespace MyDataDomain
  {
      using System;
      using System.Collections.Generic;
      using System.ComponentModel.DataAnnotations;
      using System.ComponentModel.DataAnnotations.Schema;
      using System.Data.Entity.Spatial;
  
      public partial class OrderDetail
      {
          public OrderDetail()
          {
              Calibrations = new HashSet&lt;Calibration&gt;();
              JournalEntryDatas = new HashSet&lt;JournalEntryData&gt;();
              OrderHistories = new HashSet&lt;OrderHistory&gt;();
              WorkDetails = new HashSet&lt;WorkDetail&gt;();
          }
  
          [Key]
          public long OrderID { get; set; }
  
          [StringLength(50)]  
          public string PONumber { get; set; }
  
          [Column(TypeName = "date")]
          public DateTime? Due { get; set; }
  
          [Column(TypeName = "date")]
          public DateTime? OrderDate { get; set; }
  
          [Column(TypeName = "date")]
          public DateTime? ShipDate { get; set; }
  
          [Column(TypeName = "text")]
          public string Comment { get; set; }
  
          public int? EnterByID { get; set; }
  
          public virtual ICollection&lt;Calibration&gt; Calibrations { get; set; }
  
          public virtual ICollection&lt;JournalEntryData&gt; JournalEntryDatas { get; set; }
          public virtual ICollection&lt;OrderHistory&gt; OrderHistories { get; set; }
          public virtual ICollection&lt;WorkDetail&gt; WorkDetails { get; set;      }
      }
  }
  </code></pre>
  
  <p>The rest of the classes are in similiar style, but when using the foreign key constraint it has something like this:</p>
  
  <pre><code>public virtual OrderDetail OrderDetail { get; set; }
  </code></pre>
  
  <p>since in our little world, it will revolve around the Orders.</p>
  
  <p>And the app.config:</p>
  
  <pre class="lang-html prettyprint-override"><code>&lt;?xml version="1.0" encoding="utf-8" ?&gt;
  &lt;configuration&gt;
    &lt;configSections&gt;
      &lt;!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 --&gt;
      &lt;section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0,         Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" /&gt;
    &lt;/configSections&gt;
    &lt;startup&gt;
      &lt;supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6" /&gt;
    &lt;/startup&gt;
    &lt;connectionStrings&gt;
      &lt;add name="MyDataContext" connectionString="data source=BIZSERVER\SQL2008R2DB;initial catalog=Company;persist security info=True;user id=DaBossMan;password=none_of_your_damn_business;MultipleActiveResultSets=True;App=EntityFramework" providerName="System.Data.SqlClient"/&gt;
    &lt;/connectionStrings&gt;
    &lt;entityFramework&gt;
      &lt;defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework"&gt;
        &lt;parameters&gt;
          &lt;parameter value="mssqllocaldb" /&gt;
        &lt;/parameters&gt;
      &lt;/defaultConnectionFactory&gt;
      &lt;providers&gt;
        &lt;provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" /&gt;
      &lt;/providers&gt;
    &lt;/entityFramework&gt;
  &lt;/configuration&gt;
  </code></pre>
  
  <p>So when I do this:</p>
  
  <pre><code>var context = New MyDataContext();
  var list1 = context.JournalEntryDatas.ToList();
  var list2 = context.OrderHistories.ToList();
  </code></pre>
  
  <p>An exception is thrown:</p>
  
  <blockquote>
    <p>The context cannot be used while the model is being created. This
    exception may be thrown if the context is used inside the
    <code>OnModelCreating</code> method or if the same context instance is accessed by
    multiple threads concurrently. Note that instance members of <code>DbContext</code>
    and related classes are not guaranteed to be thread safe.</p>
  </blockquote>
  
  <p>I'm going nuts here trying to figure out what I can do, and I've been reading that maybe doing a task factory could help, so then how can I use it to get the data from each table so I can populate the lists?</p>
  
  <p>OR is there another alternative or a workaround that I can use?</p>
  
  <p>EDIT: Here is the FULL stacktrace as requested (by Andez):</p>
  
  <pre><code>System.InvalidOperationException was caught
  HResult=-2146233079
  Message=The context cannot be used while the model is being created. This exception may be thrown if the context is used inside the OnModelCreating method or if the same context instance is accessed by multiple threads concurrently. Note that instance members of DbContext and related classes are not guaranteed to be thread safe.
  Source=EntityFramework
  StackTrace:
     at System.Data.Entity.Internal.LazyInternalContext.InitializeContext()
     at System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType)
     at System.Data.Entity.Internal.Linq.InternalSet`1.Initialize()
     at System.Data.Entity.Internal.Linq.InternalSet`1.GetEnumerator()
     at System.Data.Entity.Infrastructure.DbQuery`1.System.Collections.Generic.IEnumerable&lt;TResult&gt;.GetEnumerator()
     at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
     at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
     at MichellControls.JournalDataListView.JournalDataListView_Load(Object sender, EventArgs e) in c:\Users\Steve\Projects\Visual Studio 2013\Projects\MyControls\WinFormControls\JournalDataListView.cs:line 35
  InnerException: 
      // (there wasn't any InnerException)
  </code></pre>