Entity Framework 6 exception: "The context cannot be used while the model is being created"

.net c# entity-framework-6

Question

Please be patient with me while I transition from the old approach of ADO.NET to Entity Framework 6.

I'm attempting to develop a fresh WPF MVVM project as well as a few pure WinForms forms.DBContext with the EF 6 and no data-binding.

I developed a code-first database using the Visual Studio 2013 Entity framework wizard by dissecting an existing database on our company server. I then disentangled the context from the data model classes.

That's theDbContext code:

namespace EFModels
{
    public partial class MyDataContext : DbContext
    {
        public MyDataContext () : base("name=MyDataContext")
        {
        }

        public virtual DbSet<Calibration> Calibrations { get; set; }
        public virtual DbSet<OrderDetail> OrderDetails { get; set; }
        public virtual DbSet<OrderHistory> OrderHistories { get; set; } 
        public virtual DbSet<WorkDetail> WorkDetails { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {   
            modelBuilder.Entity<WorkDetail>()
                    .HasMany(e => e.Calibrations)
                    .WithOptional(e => e.WorkDetail)
                    .HasForeignKey(e => e.WorkID);  
        }
    }
}

I've divided the data classes into their own namespaces, for instance:

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<Calibration>();
            JournalEntryDatas = new HashSet<JournalEntryData>();
            OrderHistories = new HashSet<OrderHistory>();
            WorkDetails = new HashSet<WorkDetail>();
        }

        [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<Calibration> Calibrations { get; set; }

        public virtual ICollection<JournalEntryData> JournalEntryDatas { get; set; }
        public virtual ICollection<OrderHistory> OrderHistories { get; set; }
        public virtual ICollection<WorkDetail> WorkDetails { get; set;      }
    }
}

The remaining classes are designed similarly, however when the foreign key restriction is applied, it looks like this:

public virtual OrderDetail OrderDetail { get; set; }

thus the Orders will be crucial to our little world.

The app.config is also

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0,         Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
  </configSections>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6" />
  </startup>
  <connectionStrings>
    <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"/>
  </connectionStrings>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
      <parameters>
        <parameter value="mssqllocaldb" />
      </parameters>
    </defaultConnectionFactory>
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
  </entityFramework>
</configuration>

so that when I do this:

var context = New MyDataContext();
var list1 = context.JournalEntryDatas.ToList();
var list2 = context.OrderHistories.ToList();

A warning is issued:

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.

I've been reading that maybe creating a task factory might be helpful, but how can I utilize it to extract the data from each database so that I can fill the lists? I'm at my wit's end trying to figure out what I can do.

OR is there an other choice or workaround I may employ?

EDIT: As requested (by Andez), here is the whole stacktrace:

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<TResult>.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)
1
8
1/31/2017 10:07:53 AM

Popular Answer

ZZZ_tmp
1
6/15/2018 8:26:12 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow