无法设置数据库初始值设定项
本文关键字:设置 数据库 | 更新日期: 2023-09-27 17:55:47
我正在学习 ASP.NET MVC5来制作网站。我在模型文件夹中创建了几个类,并使用实体框架中的"基架功能"来创建 CRUD 页面。主页上一切都很好。但是当我单击导航栏中的"员工"链接时,此行出现错误:
public ActionResult Index()
{
return View(db.Employees.ToList());
}
错误是:
An exception of type 'System.InvalidOperationException' occurred in EntityFramework.dll but was not handled in user code
Additional information: Failed to set database initializer of type 'wms.DAL.ProductInitilizer, wms' for DbContext type 'wms.DAL.ProductContext, wms' specified in the application configuration. See inner exception for details.
这是Employee
类:
public class Employee
{
public string ID { get; set; }
public string Name { get; set; }
public string Department { get; set; }
public string Post { get; set; }
public string PS { get; set; }
public virtual ICollection<Purchase> Purchases { get; set; }
public virtual ICollection<Delivery> Deliveries { get; set; }
public virtual ICollection<Stock> Stocks { get; set; }
}
部分ProductInitializer
:
namespace wms.DAL
{
public class ProductInitializer : System.Data.Entity.DropCreateDatabaseAlways<ProductContext>
{
protected override void Seed(ProductContext context)
{
...
var employees = new List<Employee>
{
new Employee{ID="238047AF1",Name="Bill",Department="Storage",Post="worker",PS="default"},
new Employee{ID="2457656AB",Name="Bob",Department="Storage",Post="worker",PS="default"}
};
employees.ForEach(s => context.Employees.Add(s));
context.SaveChanges();
}
}
}
网络配置:
<?xml version="1.0"?>
<configuration>
<configSections>
<sectionGroup name="system.web.webPages.razor" type="System.Web.WebPages.Razor.Configuration.RazorWebSectionGroup, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
<section name="host" type="System.Web.WebPages.Razor.Configuration.HostSection, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
<section name="pages" type="System.Web.WebPages.Razor.Configuration.RazorPagesSection, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
</sectionGroup>
</configSections>
<system.web.webPages.razor>
<host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=5.2.2.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<pages pageBaseType="System.Web.Mvc.WebViewPage">
<namespaces>
<add namespace="System.Web.Mvc" />
<add namespace="System.Web.Mvc.Ajax" />
<add namespace="System.Web.Mvc.Html" />
<add namespace="System.Web.Optimization"/>
<add namespace="System.Web.Routing" />
<add namespace="wms" />
</namespaces>
</pages>
</system.web.webPages.razor>
<appSettings>
<add key="webpages:Enabled" value="false" />
</appSettings>
<system.webServer>
<handlers>
<remove name="BlockViewHandler"/>
<add name="BlockViewHandler" path="*" verb="*" preCondition="integratedMode" type="System.Web.HttpNotFoundHandler" />
</handlers>
</system.webServer>
</configuration>
这是怎么回事?我挖了很久,但找不到原因。
更新
内部异常:
System.InvalidOperationException was unhandled by user code
HResult=-2146233079
Message=Failed to set database initializer of type 'wms.DAL.ProductInitilizer, wms' for DbContext type 'wms.DAL.ProductContext, wms' specified in the application configuration. See inner exception for details.
Source=EntityFramework
StackTrace:
System.Data.Entity.Internal.InitializerConfig.TryGetInitializer(Type requiredContextType, String contextTypeName, String initializerTypeName, Boolean isDisabled, Func`1 initializerArgs, Func`3 exceptionMessage)
System.Data.Entity.Internal.InitializerConfig.<>c__DisplayClass6.<TryGetInitializerFromEntityFrameworkSection>b__1(ContextElement e)
System.Linq.Enumerable.WhereSelectEnumerableIterator`2.MoveNext()
System.Linq.Enumerable.FirstOrDefault[TSource](IEnumerable`1 source, Func`2 predicate)
System.Data.Entity.Internal.InitializerConfig.TryGetInitializerFromEntityFrameworkSection(Type contextType)
System.Data.Entity.Internal.InitializerConfig.TryGetInitializer(Type contextType)
System.Data.Entity.Infrastructure.DependencyResolution.AppConfigDependencyResolver.GetServiceFactory(Type type, String name)
System.Data.Entity.Infrastructure.DependencyResolution.AppConfigDependencyResolver.<>c__DisplayClass1.<GetService>b__0(Tuple`2 t)
System.Collections.Concurrent.ConcurrentDictionary`2.GetOrAdd(TKey key, Func`2 valueFactory)
System.Data.Entity.Infrastructure.DependencyResolution.AppConfigDependencyResolver.GetService(Type type, Object key)
System.Data.Entity.Infrastructure.DependencyResolution.ResolverChain.<>c__DisplayClass3.<GetService>b__0(IDbDependencyResolver r)
System.Linq.Enumerable.WhereSelectArrayIterator`2.MoveNext()
System.Linq.Enumerable.FirstOrDefault[TSource](IEnumerable`1 source, Func`2 predicate)
System.Data.Entity.Infrastructure.DependencyResolution.ResolverChain.GetService(Type type, Object key)
System.Data.Entity.Infrastructure.DependencyResolution.CompositeResolver`2.GetService(Type type, Object key)
System.Data.Entity.Infrastructure.DependencyResolution.DbDependencyResolverExtensions.GetService(IDbDependencyResolver resolver, Type type)
System.Data.Entity.Internal.InternalContext.PerformDatabaseInitialization()
System.Data.Entity.Internal.LazyInternalContext.<InitializeDatabase>b__4(InternalContext c)
System.Data.Entity.Internal.RetryAction`1.PerformAction(TInput input)
System.Data.Entity.Internal.LazyInternalContext.InitializeDatabaseAction(Action`1 action)
System.Data.Entity.Internal.LazyInternalContext.InitializeDatabase()
System.Data.Entity.Internal.InternalContext.Initialize()
System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType)
System.Data.Entity.Internal.Linq.InternalSet`1.Initialize()
System.Data.Entity.Internal.Linq.InternalSet`1.GetEnumerator()
System.Data.Entity.Infrastructure.DbQuery`1.System.Collections.Generic.IEnumerable<TResult>.GetEnumerator()
System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
wms.Controllers.EmployeeController.Index() Location c:'Users'cityofsky'Documents'Visual Studio 2013'Projects'wms'wms'Controllers'EmployeeController.cs:Line 21
lambda_method(Closure , ControllerBase , Object[] )
System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters)
System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters)
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters)
System.Web.Mvc.Async.AsyncControllerActionInvoker.ActionInvocation.InvokeSynchronousActionMethod()
System.Web.Mvc.Async.AsyncControllerActionInvoker.<BeginInvokeSynchronousActionMethod>b__39(IAsyncResult asyncResult, ActionInvocation innerInvokeState)
System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`2.CallEndDelegate(IAsyncResult asyncResult)
System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase`1.End()
System.Web.Mvc.Async.AsyncResultWrapper.End[TResult](IAsyncResult asyncResult, Object tag)
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult)
System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3d()
System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.<>c__DisplayClass46.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3f()
InnerException: System.TypeLoadException
HResult=-2146233054
Message=Could not load type "wms.DAL.ProductInitilizer" from assembly "wms"
Source=mscorlib
TypeName=wms.DAL.ProductInitilizer
StackTrace:
System.RuntimeTypeHandle.GetTypeByName(String name, Boolean throwOnError, Boolean ignoreCase, Boolean reflectionOnly, StackCrawlMarkHandle stackMark, IntPtr pPrivHostBinder, Boolean loadTypeFromPartialName, ObjectHandleOnStack type)
System.RuntimeTypeHandle.GetTypeByName(String name, Boolean throwOnError, Boolean ignoreCase, Boolean reflectionOnly, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean loadTypeFromPartialName)
System.RuntimeType.GetType(String typeName, Boolean throwOnError, Boolean ignoreCase, Boolean reflectionOnly, StackCrawlMark& stackMark)
System.Type.GetType(String typeName, Boolean throwOnError)
System.Data.Entity.Internal.InitializerConfig.TryGetInitializer(Type requiredContextType, String contextTypeName, String initializerTypeName, Boolean isDisabled, Func`1 initializerArgs, Func`3 exceptionMessage)
InnerException:
你发布了错误的web.config。将那个发布在项目的根目录中。尽管数据库初始值设定项也可以位于 global.asax 中。
但我看到的是异常是指"ProductInitilizer",而带有初始值设定项的类的名称是"ProductInitializer"。错别字是问题所在?