我正在使用带有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>
非常感谢,马克。
答案 0 :(得分:0)
我的猜测是你的初始化类是内部的。在我的项目中,我从另一个程序集加载它,它无法看到它。一旦我改为公开,它就像魔术一样。 我认为即使你把所有东西放在同一个组件中也可能是真的。
答案 1 :(得分:0)
我的问题与我的连接字符串有关。
男人,在尝试以下链接后,我没有成功。我试图连接到我的SQLEXPRESS实例。我试过了:
error loading database initializer with EF6
Reset Entity-Framework Migrations
试试这个 - 这最终对我有用。如果不使用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/