4

我正在使用 .NET4.5 和 Entity Framework 6 alpha3 创建一个 Web 应用程序,该应用程序使用新的 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>

非常感谢,马克。

4

2 回答 2

0

我的猜测是您的初始化程序类是内部的。在我的项目中,我从另一个程序集中加载它,但它看不到它。一旦我改为公开,它就像魔术一样工作。我认为即使您将所有内容都放在同一个程序集中,它也可能是正确的。

于 2013-08-26T10:16:24.273 回答
0

我的问题与我的连接字符串有关。

伙计,在尝试了以下链接后,我没有成功。我试图连接到我的 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/

于 2016-04-13T17:53:20.243 回答