錯誤“無法設置MyNamespace.MyCustomInitializer類型的數據庫初始化程序,MyAssembly”無法加載MyContext類型

entity-framework entity-framework-6 webforms

我正在使用帶有Entity Framework 6 alpha3的.NET4.5創建一個使用新SQL Compact數據庫的Web應用程序。該數據庫尚不存在。

我在網絡表單中有以下代碼:

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;
}

JournalistContext派生自DbContext的地方。它創建了JournalistContext的實例ok,但是當執行下一行時,它會拋出下面的異常。我猜測因為數據庫不存在,它會嘗試調用初始化程序,但這會失敗。

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)

如此處所述http://msdn.microsoft.com/en-us/data/jj556606我創建了一個自定義數據庫初始化程序,它目前是一個空白類:

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

    }

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

我的web.config文件引用此初始化程序,如下所示:

  <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>

我很難過!有任何想法嗎?

我注意到的另一件事是:這些行出現在我的web.config文件中。我不確定它們是如何添加的,或者為什麼。

  <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>

非常感謝,馬克。

熱門答案

我的問題與我的連接字符串有關。

男人,在嘗試以下鏈接後,我沒有成功。我試圖連接到我的SQLEXPRESS實例。我試過了:

使用EF6加載數據庫初始化程序時出錯

重置實體框架遷移

試試這個 - 這最終對我有用。如果您不使用localdb,請用SqlExpress / SqlServer實例替換數據源。

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

請隨意發表評論,如果您仍然遇到此問題,我可以繼續嘗試提供幫助。

這是我最終找到的資源,幫助我了解了很多關於我正在做的事情。

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




許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow
這個KB合法嗎? 是的,了解原因
許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow
這個KB合法嗎? 是的,了解原因