错误加载数据库初始化与EF6 [英] error loading database initializer with EF6

查看:438
本文介绍了错误加载数据库初始化与EF6的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在努力遵循本教程... <一个href=\"http://www.asp.net/mvc/tutorials/getting-started-with-ef-using-mvc/creating-an-entity-framework-data-model-for-an-asp-net-mvc-application\" rel=\"nofollow\">http://www.asp.net/mvc/tutorials/getting-started-with-ef-using-mvc/creating-an-entity-framework-data-model-for-an-asp-net-mvc-application但我不断收到以下错误...

I have been trying to follow this tutorial ... http://www.asp.net/mvc/tutorials/getting-started-with-ef-using-mvc/creating-an-entity-framework-data-model-for-an-asp-net-mvc-application but I keep getting the following error ...

system.invalidoperationexception = {无法设置类型的DbContext类型婚礼preparations.Dal.WeddingInitializer,KevinLisaWedding'数据库初始化婚礼preparations.Dal.WeddingContext在应用程序配置中指定。见内部异常的详细信息。}

system.invalidoperationexception = {"Failed to set database initializer of type 'WeddingPreparations.Dal.WeddingInitializer, KevinLisaWedding' for DbContext type 'WeddingPreparations.Dal.WeddingContext' specified in the application configuration. See inner exception for details."}

该内部异常是...

{未能从程序集加载类型婚礼preparations.Dal.WeddingContext'的EntityFramework,版本6.0.0.0 =文化=中性公钥= b77a5c561934e089'。:婚礼preparations.Dal .WeddingContext}

{"Could not load type 'WeddingPreparations.Dal.WeddingContext' from assembly 'EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'.":"WeddingPreparations.Dal.WeddingContext"}

堆栈跟踪为...

   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.Infrastructure.DependencyResolution.AppConfigDependencyResolver.GetServiceFactory(Type type, String name)
   at System.Data.Entity.Infrastructure.DependencyResolution.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.Infrastructure.DependencyResolution.AppConfigDependencyResolver.GetService(Type type, Object key)
   at System.Data.Entity.Infrastructure.DependencyResolution.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.Infrastructure.DependencyResolution.ResolverChain.GetService(Type type, Object key)
   at System.Data.Entity.Infrastructure.DependencyResolution.CompositeResolver`2.GetService(Type type, Object key)
   at System.Data.Entity.Infrastructure.DependencyResolution.DbDependencyResolverExtensions.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.GetEnumerator()
   at System.Data.Entity.Infrastructure.DbQuery`1.System.Collections.Generic.IEnumerable<TResult>.GetEnumerator()
   at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
   at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
   at KevinLisaWedding.Controllers.HomeController.Index() in c:\Users\kdonde\Documents\Visual Studio 2013\Projects\KevinLisaWedding\KevinLisaWedding\Controllers\HomeController.cs:line 14
   at lambda_method(Closure , ControllerBase , Object[] )
   at System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters)
   at System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters)
   at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters)
   at System.Web.Mvc.Async.AsyncControllerActionInvoker.ActionInvocation.InvokeSynchronousActionMethod()
   at System.Web.Mvc.Async.AsyncControllerActionInvoker.<BeginInvokeSynchronousActionMethod>b__36(IAsyncResult asyncResult, ActionInvocation innerInvokeState)
   at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`2.CallEndDelegate(IAsyncResult asyncResult)
   at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase`1.End()
   at System.Web.Mvc.Async.AsyncResultWrapper.End[TResult](IAsyncResult asyncResult, Object tag)
   at System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult)
   at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3c()
   at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.<>c__DisplayClass45.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3e()

我还搜查高和低为什么我收到这个错误没有任何运气,我已经下载完成的项目相比其矿山没有任何运气。

I've also searched high and low for why I am getting this error without any luck and I've downloaded the completed project and compared it to mine without any luck.

我目前的code如下。

My current code is as follows.

在婚礼preparations项目...

In the WeddingPreparations project ...

namespace WeddingPreparations.Dal
{
    public class WeddingContext : DbContext
    {
        public WeddingContext()
            : base("WeddingContext")  
        {

        }

        // Any entities reference by this class will be implicitly included.
        public DbSet<Invitee> Invitees { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
            //base.OnModelCreating(modelBuilder);
        }
    }
}

namespace WeddingPreparations.Dal
{
    public class WeddingInitializer : System.Data.Entity.DropCreateDatabaseIfModelChanges<WeddingContext>
    {
        protected override void Seed(WeddingContext context)
        {
            //base.Seed(context);
            var invitees = new List<Invitee>
            {
                new Invitee{ FirstName= "FName1", LastName= "LName1", Attending = true, HotelRoomRequired= true, Notes="I'm the groom! :)"},
                new Invitee{ FirstName= "FName2", LastName= "LName2", Attending = true, HotelRoomRequired= true, Notes="I'm the bride! :)"}

            };
            invitees.ForEach(i => context.Invitees.Add(i));
            context.SaveChanges();
        }
    }
}

我在这个项目模型如下:

My model in this project is as follows

namespace WeddingPreparations.Models
{
    public class Invitee
    {
        public int Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public bool Attending { get; set; }
        public bool HotelRoomRequired { get; set; }
        public string Notes { get; set; }
     }
}

在MVC项目我有以下的web.config文件...

In the mvc project I have the following web.config file ...

<?xml version="1.0" encoding="utf-8"?>
<!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=301880
  -->
<configuration>
  <configSections>

    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
  <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 --></configSections>
  <connectionStrings>
    <add name="WeddingContext" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=WeddingInvites;Integrated Security=SSPI;" providerName="System.Data.SqlClient" />
  </connectionStrings>
  <appSettings>
    <add key="webpages:Version" value="3.0.0.0" />
    <add key="webpages:Enabled" value="false" />
    <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />
  </appSettings>
  <system.web>
    <compilation debug="true" targetFramework="4.5" />
    <httpRuntime targetFramework="4.5" />
  </system.web>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-5.0.0.0" newVersion="5.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Optimization" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="1.1.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-1.5.2.14234" newVersion="1.5.2.14234" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Ninject" publicKeyToken="c7192dc5380945e7" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-3.2.0.0" newVersion="3.2.0.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
  <system.webServer>
    <handlers>
      <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
      <remove name="OPTIONSVerbHandler" />
      <remove name="TRACEVerbHandler" />
      <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
    </handlers>
  </system.webServer>
  <entityFramework>
    <contexts>
      <context type="WeddingPreparations.Dal.WeddingContext">
        <databaseInitializer type="WeddingPreparations.Dal.WeddingInitializer, KevinLisaWedding" />
      </context>
    </contexts>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework" >
    <parameters>
      <parameter value="v11.0"/>
    </parameters>
    </defaultConnectionFactory>
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
  </entityFramework>
</configuration>

和在我家的控制器,我执行以下code ...

And in my home controller I'm executing the following code ...

WeddingPreparations.Dal.WeddingContext ctx = new WeddingPreparations.Dal.WeddingContext();
var x = ctx.Invitees.ToList();

这是为了创造,如果我没有弄错的数据库,并在初始化中指定的数据种子吧...但是我得到的是一个错误,我似乎无法推测出来的......方向AP preciated。

which is supposed to create the database if I'm not mistaking and seed it with the data specified in the initializer ... however all I get is that error and I can't seem to figure it out ... any direction is appreciated.

我试图重新创建项目为一体,就像他们在本教程中没有和,但我仍然落得同样的错误。有一定有一些code失踪......无论我错过了......或者教程只是没有它。

I tried recreating the project as one just like they did in the tutorial and but i still end up with the same error. There's gotta be some code missing ... either I missed it ... or the tutorial just doesn't have it.

推荐答案

在你的的web.config 文件,你有这样的:

In your web.config file you have this:

<contexts>
    <context type="WeddingPreparations.Dal.WeddingContext">
        <databaseInitializer type="WeddingPreparations.Dal.WeddingInitializer, KevinLisaWedding" />
    </context>
</contexts>

这说找一个叫婚礼preparations.Dal.WeddingInitializer 在叫拼装 KevinLisaWedding 类。当你的组件名为婚礼preparations 您需要的配置改成这样:

This says look for a class called WeddingPreparations.Dal.WeddingInitializer in the assembly called KevinLisaWedding. As your assembly is called WeddingPreparations you need to change the config to this:

<contexts>
    <context type="WeddingPreparations.Dal.WeddingContext, WeddingPreparations">
        <databaseInitializer type="WeddingPreparations.Dal.WeddingInitializer, WeddingPreparations" />
    </context>
</contexts>

这篇关于错误加载数据库初始化与EF6的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆