Error "Failed to set database initializer of type MyNamespace.MyCustomInitializer, MyAssembly" could not load MyContext type

entity-framework entity-framework-6 webforms

Question

I'm creating a web app using .NET4.5 with Entity Framework 6 alpha3 that uses a new SQL Compact database. The database does not yet exist.

I have the following code in a web form:

public IQueryable<Job> listJobs_GetData()
{
    var db = new JournalistContext();
    IQueryable<Job> query = db.Jobs.Where(d => d.JobStart > DateTime.Now)
        .OrderBy(s => s.JobStart)
        .Take(10);
    return query;
}

where the JournalistContext derives from DbContext. It creates the instance of JournalistContext ok, but when executing the next line, it throws the exception below. I'm guessing as the database doesnt exist, it tries to call the initializer, but this fails.

System.InvalidOperationException was unhandled by user code
  HResult=-2146233079
  Message=Failed to set database initializer of type 'TSJ.Models.MyCustomInitializer, TSJ' for DbContext type 'TSJ.JournalistContext, TSJ' specified in the application configuration. See inner exception for details.
  Source=EntityFramework
  StackTrace:
       at System.Data.Entity.Internal.InitializerConfig.TryGetInitializer(Type requiredContextType, String contextTypeName, String initializerTypeName, Boolean isDisabled, Func`1 initializerArgs, Func`3 exceptionMessage)
       at System.Data.Entity.Internal.InitializerConfig.<>c__DisplayClass6.<TryGetInitializerFromEntityFrameworkSection>b__1(ContextElement e)
       at System.Linq.Enumerable.WhereSelectEnumerableIterator`2.MoveNext()
       at System.Linq.Enumerable.FirstOrDefault[TSource](IEnumerable`1 source, Func`2 predicate)
       at System.Data.Entity.Internal.InitializerConfig.TryGetInitializerFromEntityFrameworkSection(Type contextType)
       at System.Data.Entity.Internal.InitializerConfig.TryGetInitializer(Type contextType)
       at System.Data.Entity.Config.AppConfigDependencyResolver.GetServiceFactory(Type type, String name)
       at System.Data.Entity.Config.AppConfigDependencyResolver.<>c__DisplayClass1.<GetService>b__0(Tuple`2 t)
       at System.Collections.Concurrent.ConcurrentDictionary`2.GetOrAdd(TKey key, Func`2 valueFactory)
       at System.Data.Entity.Config.AppConfigDependencyResolver.GetService(Type type, Object key)
       at System.Data.Entity.Config.ResolverChain.<>c__DisplayClass3.<GetService>b__0(IDbDependencyResolver r)
       at System.Linq.Enumerable.WhereSelectArrayIterator`2.MoveNext()
       at System.Linq.Enumerable.FirstOrDefault[TSource](IEnumerable`1 source, Func`2 predicate)
       at System.Data.Entity.Config.ResolverChain.GetService(Type type, Object key)
       at System.Data.Entity.Config.CompositeResolver`2.GetService(Type type, Object key)
       at System.Data.Entity.Config.IDbDependencyResolverExtensions.GetService(IDbDependencyResolver resolver, Type type)
       at System.Data.Entity.Internal.InternalContext.PerformDatabaseInitialization()
       at System.Data.Entity.Internal.LazyInternalContext.<InitializeDatabase>b__4(InternalContext c)
       at System.Data.Entity.Internal.RetryAction`1.PerformAction(TInput input)
       at System.Data.Entity.Internal.LazyInternalContext.InitializeDatabaseAction(Action`1 action)
       at System.Data.Entity.Internal.LazyInternalContext.InitializeDatabase()
       at System.Data.Entity.Internal.InternalContext.Initialize()
       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.get_InternalContext()
       at System.Data.Entity.Infrastructure.DbQuery`1.System.Linq.IQueryable.get_Provider()
       at System.Linq.Queryable.Where[TSource](IQueryable`1 source, Expression`1 predicate)
       at TSJ.MainOverview.listJobs_GetData() in ....\Visual Studio 2012\Projects\TSJ\TSJ\MainOverview.aspx.cs:line 27
  InnerException: System.TypeLoadException
       HResult=-2146233054
       Message=Could not load type 'TSJ.JournalistContext' from assembly 'TSJ'.
       Source=mscorlib
       TypeName=TSJ.JournalistContext
       StackTrace:
            at System.RuntimeTypeHandle.GetTypeByName(String name, Boolean throwOnError, Boolean ignoreCase, Boolean reflectionOnly, StackCrawlMarkHandle stackMark, IntPtr pPrivHostBinder, Boolean loadTypeFromPartialName, ObjectHandleOnStack type)
            at System.RuntimeTypeHandle.GetTypeByName(String name, Boolean throwOnError, Boolean ignoreCase, Boolean reflectionOnly, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean loadTypeFromPartialName)
            at System.RuntimeType.GetType(String typeName, Boolean throwOnError, Boolean ignoreCase, Boolean reflectionOnly, StackCrawlMark& stackMark)
            at System.Type.GetType(String typeName, Boolean throwOnError)
            at System.Data.Entity.Internal.InitializerConfig.TryGetInitializer(Type requiredContextType, String contextTypeName, String initializerTypeName, Boolean isDisabled, Func`1 initializerArgs, Func`3 exceptionMessage)

As described here http://msdn.microsoft.com/en-us/data/jj556606 I have created a custom database initializer, which presently is a blank class:

    internal sealed class MyCustomInitializer : MigrateDatabaseToLatestVersion<JournalistContext, TSJ.Migrations.Configuration>
    {

    }

    public class JournalistContext : DbContext 
    {
        public JournalistContext() : base("TSJ")
        {
        }
...

My web.config file references this initializer as follows:

  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlCeConnectionFactory, EntityFramework">
      <parameters>
        <parameter value="System.Data.SqlServerCe.4.0" />
      </parameters>
    </defaultConnectionFactory>
    <contexts>
      <context type="TSJ.JournalistContext, TSJ">
        <databaseInitializer type="TSJ.Models.MyCustomInitializer, TSJ" />
      </context>
    </contexts>
    <providers>
      <provider invariantName="System.Data.SqlServerCe.4.0" type="System.Data.Entity.SqlServerCompact.SqlCeProviderServices, EntityFramework.SqlServerCompact, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
    </providers>
  </entityFramework>

I'm stumped! Any ideas?

Another thing I've noticed: these lines have appeared in my web.config file. I'm not sure how they were added, or why.

  <system.data>
    <DbProviderFactories>
      <remove invariant="System.Data.SqlServerCe.4.0" />
      <add name="Microsoft SQL Server Compact Data Provider 4.0" invariant="System.Data.SqlServerCe.4.0" description=".NET Framework Data Provider for Microsoft SQL Server Compact" type="System.Data.SqlServerCe.SqlCeProviderFactory, System.Data.SqlServerCe, Version=4.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91" />
    </DbProviderFactories>
  </system.data>

many thanks, Mark.

Popular Answer

My problem was related to my connection string.

Man, after trying the following links, I had no success. I was trying to connect to my SQLEXPRESS instance. I tried:

error loading database initializer with EF6

Reset Entity-Framework Migrations

Try this instead - this finally worked for me. Replace the data source with your SqlExpress/SqlServer instance if you aren't using localdb.

Enable-Migrations -ConnectionString "Data Source=.\SQLEXPRESS;Initial Catalog=[your database name];User Id=[your user name];Password=[your password];Integrated Security=SSPI;" -ConnectionProviderName "System.Data.SqlClient" -Force -Verbose

Add-Migration -Name "Initial" -ConnectionString "Data Source=.\SQLEXPRESS;Initial Catalog=[your database name];User Id=[your user name];Password=[your password];Integrated Security=SSPI;" -ConnectionProviderName "System.Data.SqlClient" -Force -Verbose

Update-Database -Force -ConnectionString "Data Source=.\SQLEXPRESS;Initial Catalog=[your database name];User Id=[your user name];Password=[your password];Integrated Security=SSPI;" -ConnectionProviderName "System.Data.SqlClient" -Verbose

Feel free to comment and I can continue trying to assist if you're still having this problem.

This was the resource I finally found that helped me understand a lot about what I'm doing.

https://coding.abel.nu/2012/03/ef-migrations-command-reference/




Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why