The context cannot be used while the model is being created

I was able to resolve this issue by adding

MultipleActiveResultSets=true

to the my EF connection string.

I fixed it by adding this multiple thread connection parameter.


I have experienced this issue in the past and usually it was due not using the latest version + referencing issue.

Try and get the newest EF version from NuGet for all your projects and see if the error goes away:
http://blogs.msdn.com/b/adonet/archive/2012/02/09/ef-4-3-released.aspx

UPDATE
Another reason for this error can be that while you create the context the first time and therefore cause the model to be created you create another context on a separate thread. You will have to wait for other context instances to be created after the model creation has completed.


I had this error as well but was able to solve it by declaring a local variable context inside of each thread rather than using the one I had declared globally.

    Parallel.ForEach(myList, l=>
    {
        MyContext _db = new MyContext();
        // do some stuff....
        _db.Model.Add(....);
        _db.SaveChanges();

    });

Make sure you also set MultipleActiveResultSets=true in your connection string as described above.


In your App.Config file under connectionstrings you had a forward slash (./SQLEXPRESS). Change this to a backslash .\SQLEXPRESS like so:

<add name="DatabaseContext" connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=ProjectCode;Integrated Security=SSPI;" providerName="System.Data.SqlClient" />