7

Ho cercato di seguire questo 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 ma continuo a ricevere il seguente errore ...errore del database di carico initializer con EF6

System.InvalidOperationException = { "Impossibile impostare banca dati di inizializzazione di tipo 'WeddingPreparations.Dal.WeddingInitializer, KevinLisaWedding' per DbContext tipo 'WeddingPreparations.Dal.WeddingContext' specificato nella configurazione dell'applicazione . Vedere eccezione interna per i dettagli. "}

L'eccezione interna è ...

{ "Impossibile caricare il tipo 'WeddingPreparations.Dal.WeddingContext' dal assembly 'EntityFramework, Version = 6.0.0.0, Culture = neutral, PublicKeyToken = b77a5c561934e089'." : "WeddingPreparations.Dal.WeddingContext"}

L'analisi dello stack è ...

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() 

ho cercato anche di alta e bassa per il motivo per cui sto ottenendo questo errore senza alcuna fortuna un Ho scaricato il progetto completato e l'ho paragonato al mio senza fortuna.

Il mio codice corrente è il seguente.

Nel progetto WeddingPreparations ...

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); 
     } 
    } 
} 

e

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(); 
     } 
    } 
} 

Il mio modello in questo progetto è la seguente

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; } 
    } 
} 

Nel progetto MVC Ho il seguente web File .config ...

<?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> 

E nel mio controller a casa sto eseguendo il seguente codice ...

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

che dovrebbe creare il database se non sto sbagliando e seminare con i dati specificati nel inizializzatore ... comunque tutto quello che ottengo è quell'errore e non riesco a capirlo ... ogni direzione è apprezzata.

Aggiornamento

ho provato a ricreare il progetto come uno proprio come hanno fatto nel tutorial e ma ho ancora finire con lo stesso errore. Ci deve essere del codice mancante ... o l'ho perso ... o il tutorial non ce l'ha.

+0

Qual è il nome dell'assieme che si sta creando? E 'WeddingPreparations o KevinLisaWedding? – DavidG

+0

KevinLisaWedding è il progetto del sito Web e WeddingPreparations è la DLL con i modelli di entità e il contesto di entità ecc. –

+1

Funziona se si imposta l'inizializzatore nel costruttore 'DbContext', come segue:' Database.SetInitializer (new WeddingInitializer()) ; ' – david004

risposta

21

Nel file web.config avete questo:

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

Questo dice cercare una classe chiamata WeddingPreparations.Dal.WeddingInitializer nell'assemblea chiamata KevinLisaWedding.Poiché il tuo assembly è chiamato WeddingPreparations devi modificare la configurazione in questo modo:

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

DavidG In realtà l'avevo provato un paio di volte. L'ho appena cambiato e continuo a ricevere lo stesso errore. Grazie per il suggerimento. –

+0

Prova a specificare anche il tipo di contesto. Ho aggiornato la mia risposta. – DavidG

+0

Hell yes !!! Ha funzionato. Grazie. –

Problemi correlati