实体框架:无法加载上下文

时间:2018-04-14 17:20:38

标签: c# .net asp.net-mvc entity-framework entity-framework-6

我正在设置实体框架但遇到了一些麻烦。我正在使用MVC,EF 6.0,.net Framework 4.5.1

在我的网络配置中,我在entityFramework节点中有这个:

<contexts>
      <context type="MyApp.Data.UserContext">
        <databaseInitializer type="MyApp.Data.UserContextInit" />
      </context>
    </contexts>

但是,当我尝试运行我的应用时,我收到以下错误:

Could not load type 'MyApp.Data.UserContext' from assembly 'EntityFramework'.

以下是来自web config的完整entityFramework节点:

<entityFramework>
    <contexts>
      <context type="MyApp.Data.UserContext">
        <databaseInitializer type="MyApp.Data.UserContextInit" />
      </context>
    </contexts>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
      <parameters>
        <parameter value="mssqllocaldb" />
      </parameters>
    </defaultConnectionFactory>
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
  </entityFramework>

这是整个堆栈跟踪:

[TypeLoadException: Could not load type 'MyApp.Data.UserContext' from assembly 'EntityFramework'.]
   System.RuntimeTypeHandle.GetTypeByName(String name, Boolean throwOnError, Boolean ignoreCase, Boolean reflectionOnly, StackCrawlMarkHandle stackMark, IntPtr pPrivHostBinder, Boolean loadTypeFromPartialName, ObjectHandleOnStack type) +0
   System.RuntimeTypeHandle.GetTypeByName(String name, Boolean throwOnError, Boolean ignoreCase, Boolean reflectionOnly, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean loadTypeFromPartialName) +70
   System.RuntimeType.GetType(String typeName, Boolean throwOnError, Boolean ignoreCase, Boolean reflectionOnly, StackCrawlMark& stackMark) +40
   System.Type.GetType(String typeName, Boolean throwOnError) +34
   System.Data.Entity.Internal.InitializerConfig.TryGetInitializer(Type requiredContextType, String contextTypeName, String initializerTypeName, Boolean isDisabled, Func`1 initializerArgs, Func`3 exceptionMessage) +39

[InvalidOperationException: Failed to set database initializer of type 'MyApp.Data.UserContextInit' for DbContext type 'MyApp.Data.UserContext, EntityFramework' specified in the application configuration. See inner exception for details.]
   System.Data.Entity.Internal.InitializerConfig.TryGetInitializer(Type requiredContextType, String contextTypeName, String initializerTypeName, Boolean isDisabled, Func`1 initializerArgs, Func`3 exceptionMessage) +232
   System.Data.Entity.Internal.<>c__DisplayClass6.<TryGetInitializerFromEntityFrameworkSection>b__1(ContextElement e) +199
   System.Linq.WhereSelectEnumerableIterator`2.MoveNext() +164
   System.Linq.Enumerable.FirstOrDefault(IEnumerable`1 source, Func`2 predicate) +94
   System.Data.Entity.Internal.InitializerConfig.TryGetInitializerFromEntityFrameworkSection(Type contextType) +250
   System.Data.Entity.Internal.InitializerConfig.TryGetInitializer(Type contextType) +18
   System.Data.Entity.Infrastructure.DependencyResolution.AppConfigDependencyResolver.GetServiceFactory(Type type, String name) +439
   System.Data.Entity.Infrastructure.DependencyResolution.<>c__DisplayClass1.<GetService>b__0(Tuple`2 t) +42
   System.Collections.Concurrent.ConcurrentDictionary`2.GetOrAdd(TKey key, Func`2 valueFactory) +72
   System.Data.Entity.Infrastructure.DependencyResolution.AppConfigDependencyResolver.GetService(Type type, Object key) +140
   System.Data.Entity.Infrastructure.DependencyResolution.<>c__DisplayClass3.<GetService>b__0(IDbDependencyResolver r) +19
   System.Linq.WhereSelectArrayIterator`2.MoveNext() +58
   System.Linq.Enumerable.FirstOrDefault(IEnumerable`1 source, Func`2 predicate) +94
   System.Data.Entity.Infrastructure.DependencyResolution.ResolverChain.GetService(Type type, Object key) +160
   System.Data.Entity.Infrastructure.DependencyResolution.CompositeResolver`2.GetService(Type type, Object key) +39
   System.Data.Entity.Infrastructure.DependencyResolution.DbDependencyResolverExtensions.GetService(IDbDependencyResolver resolver, Type type) +56
   System.Data.Entity.Internal.InternalContext.PerformDatabaseInitialization() +125
   System.Data.Entity.Internal.LazyInternalContext.<InitializeDatabase>b__4(InternalContext c) +7
   System.Data.Entity.Internal.RetryAction`1.PerformAction(TInput input) +110
   System.Data.Entity.Internal.LazyInternalContext.InitializeDatabaseAction(Action`1 action) +198
   System.Data.Entity.Internal.LazyInternalContext.InitializeDatabase() +73
   System.Data.Entity.Internal.InternalContext.Initialize() +30
   System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType) +16
   System.Data.Entity.Internal.Linq.InternalSet`1.Initialize() +53
   System.Data.Entity.Internal.Linq.InternalSet`1.GetEnumerator() +15
   System.Data.Entity.Infrastructure.DbQuery`1.System.Collections.Generic.IEnumerable<TResult>.GetEnumerator() +53
   System.Collections.Generic.List`1..ctor(IEnumerable`1 collection) +375
   System.Linq.Enumerable.ToList(IEnumerable`1 source) +58
   MyApp.WebMS.Controllers.HomeController.Index() in C:\Users\Ben Donnelly\Documents\Visual Studio 2017\Projects\TechTest\MyApp\MyApp.WebMS\Controllers\HomeController.cs:18
   lambda_method(Closure , ControllerBase , Object[] ) +61
   System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) +14
   System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +157
   System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +27
   System.Web.Mvc.Async.AsyncControllerActionInvoker.<BeginInvokeSynchronousActionMethod>b__39(IAsyncResult asyncResult, ActionInvocation innerInvokeState) +22
   System.Web.Mvc.Async.WrappedAsyncResult`2.CallEndDelegate(IAsyncResult asyncResult) +29
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
   System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) +32
   System.Web.Mvc.Async.AsyncInvocationWithFilters.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3d() +50
   System.Web.Mvc.Async.<>c__DisplayClass46.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3f() +228
   System.Web.Mvc.Async.<>c__DisplayClass33.<BeginInvokeActionMethodWithFilters>b__32(IAsyncResult asyncResult) +10
   System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +10
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
   System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult) +34
   System.Web.Mvc.Async.<>c__DisplayClass2b.<BeginInvokeAction>b__1c() +26
   System.Web.Mvc.Async.<>c__DisplayClass21.<BeginInvokeAction>b__1e(IAsyncResult asyncResult) +100
   System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +10
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
   System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +27
   System.Web.Mvc.Controller.<BeginExecuteCore>b__1d(IAsyncResult asyncResult, ExecuteCoreState innerState) +13
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +29
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
   System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +36
   System.Web.Mvc.Controller.<BeginExecute>b__15(IAsyncResult asyncResult, Controller controller) +12
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +22
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
   System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +26
   System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +10
   System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__5(IAsyncResult asyncResult, ProcessRequestState innerState) +21
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +29
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
   System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +28
   System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9
   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +9748665
   System.Web.HttpApplication.ExecuteStepImpl(IExecutionStep step) +48
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +159

我一直在关注微软文档来设置它,我注意到的一件事是他们在我首先显示的上下文节点中指定了上下文的完整路径之后放置了程序集。 这是文档链接; https://docs.microsoft.com/en-us/aspnet/mvc/overview/getting-started/getting-started-with-ef-using-mvc/creating-an-entity-framework-data-model-for-an-asp-net-mvc-application#main

1 个答案:

答案 0 :(得分:2)

错误几乎说明了问题,代码正在寻找您在错误的程序集中指定的类型。要解决这个问题,您需要使用可以找到的程序集来限定您的类型。例如:

<databaseInitializer type="MyApp.Data.UserContextInit, MyAssemblyName" />