locked
doing something wrong with databaseInitializer in the ContosoUniversity tutorial RRS feed

  • Question

  • User1292113567 posted

    Summary of the problem I am having:

    I am going through Microsoft's Code First tutorial for EF6; I have reached the point where I have set up the scaffolding for the Student model and should be able to build and launch the site and view the Student tab, however I am not. It fails trying to drop and re-initialize the database.

    I am using Visual Studio 2015, I am in Windows 10 64 bit, and I am using SQLEXPRESS instead of LocalDB (I already needed SQLEXPRESS and I prefer knowing where my db is hiding when I'm trying to figure out what I did wrong).

    Error I am receiving:

    FileNotFoundException: Could not load file or assembly 'ContosoUniversity' or one of its dependencies. The system cannot find the file specified.]
       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 'ContosoUniversity.DAL.SchoolInitializer,ContosoUniversity' for DbContext type 'ContosoUniversity.DAL.SchoolContext,ContosoUniversity' 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.GetEntitySetAndBaseTypeForType(Type entityType) +28
       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
       ConsotoUniversity.Controllers.StudentController.Index() in D:\GitHub\ConsotoUniversity\ConsotoUniversity\Controllers\StudentController.cs:21
       lambda_method(Closure , ControllerBase , Object[] ) +62
       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() +9874329
       System.Web.HttpApplication.ExecuteStepImpl(IExecutionStep step) +48
       System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +159

    My research:

    I have rebuilt the tutorial several times, copying and pasting code instead of typing it in to make sure I wasn't typo-ing something.

    I have searched on the inner exception and found another user on this site having problems at the same point, and they received several suggestions that their Web.config might have a typo referring to the SchoolContext or SchoolInitializer, so I went back and re-examined those sections specifically, and copy-pasted the namespaces from SchoolInitializer to SchoolContext and to Web.config, along with copy-pasting the class names, to try to account for a typo.

    I've confirmed my SQLEXPRESS server is running. I have confirmed there is no existing ContosoUniversity db in my MySQL db.

    My code:

    Web.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>
        <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
        <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="SchoolContext" connectionString="Data Source=CAOTT631628\SQLEXPRESS;Initial Catalog=ContosoUniversityData;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.2" />
        <httpRuntime targetFramework="4.5.2" />
        <httpModules>
          <add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" />
        </httpModules>
      </system.web>
      <runtime>
        <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
          <dependentAssembly>
            <assemblyIdentity name="Newtonsoft.Json" culture="neutral" publicKeyToken="30ad4fe6b2a6aeed" />
            <bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.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="WebGrease" publicKeyToken="31bf3856ad364e35" />
            <bindingRedirect oldVersion="0.0.0.0-1.5.2.14234" newVersion="1.5.2.14234" />
          </dependentAssembly>
          <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.WebPages" 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.2.3.0" newVersion="5.2.3.0" />
          </dependentAssembly>
        </assemblyBinding>
      </runtime>
      <system.codedom>
        <compilers>
          <compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:6 /nowarn:1659;1699;1701" />
          <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:14 /nowarn:41008 /define:_MYTYPE=\&quot;Web\&quot; /optionInfer+" />
        </compilers>
      </system.codedom>
      <system.webServer>
        <validation validateIntegratedModeConfiguration="false" />
        <modules>
          <remove name="ApplicationInsightsWebTracking" />
          <add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" preCondition="managedHandler" />
        </modules>
      </system.webServer>
      <entityFramework>
        <contexts>
          <context type="ContosoUniversity.DAL.SchoolContext,ContosoUniversity">
            <databaseInitializer type="ContosoUniversity.DAL.SchoolInitializer,ContosoUniversity" />
          </context>
        </contexts>
        <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
        <providers>
          <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
        </providers>
      </entityFramework>
    </configuration>

    SchoolContext.cs

    using ContosoUniversity.Models;
    using System.Data.Entity;
    using System.Data.Entity.ModelConfiguration.Conventions;
    namespace ContosoUniversity.DAL
    {
        public class SchoolContext : DbContext
        {
            public SchoolContext() : base("SchoolContext")
            {
            }
            public DbSet<Student> Students { get; set; }
            public DbSet<Enrollment> Enrollments { get; set; }
            public DbSet<Course> Courses { get; set; }
            protected override void OnModelCreating(DbModelBuilder modelBuilder)
            {
                modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
            }
        }
    }


    SchoolInitializer.cs

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Data.Entity;
    using ContosoUniversity.Models;
    namespace ContosoUniversity.DAL
    {
        public class SchoolInitializer : System.Data.Entity.
        DropCreateDatabaseIfModelChanges<SchoolContext>
        {
            protected override void Seed(SchoolContext context)
            {
                var students = new List<Student>
                {
                new
                Student{FirstMidName="Carson",LastName="Alexander",EnrollmentDate=DateTime.Parse("2005-09-01")},
                new
                Student{FirstMidName="Meredith",LastName="Alonso",EnrollmentDate=DateTime.Parse("2002-09-01")},
                new
                Student{FirstMidName="Arturo",LastName="Anand",EnrollmentDate=DateTime.Parse("2003-09-01")},
                new
                Student{FirstMidName="Gytis",LastName="Barzdukas",EnrollmentDate=DateTime.Parse("2002-09-01")},
                new
                Student{FirstMidName="Yan",LastName="Li",EnrollmentDate=DateTime.Parse("2002-09-01")},
                new
                Student{FirstMidName="Peggy",LastName="Justice",EnrollmentDate=DateTime.Parse("2001-09-01")},
                new
                Student{FirstMidName="Laura",LastName="Norman",EnrollmentDate=DateTime.Parse("2003-09-01")},
                new
                Student{FirstMidName="Nino",LastName="Olivetto",EnrollmentDate=DateTime.Parse("2005-09-01")}
                };
                            students.ForEach(s => context.Students.Add(s));
                            context.SaveChanges();
                            var courses = new List<Course>
                {
                new Course{CourseID=1050,Title="Chemistry",Credits=3,},
                new Course{CourseID=4022,Title="Microeconomics",Credits=3,},
                new Course{CourseID=4041,Title="Macroeconomics",Credits=3,},
                new Course{CourseID=1045,Title="Calculus",Credits=4,},
                new Course{CourseID=3141,Title="Trigonometry",Credits=4,},
                new Course{CourseID=2021,Title="Composition",Credits=3,},
                new Course{CourseID=2042,Title="Literature",Credits=4,}
                };
                            courses.ForEach(s => context.Courses.Add(s));
                            context.SaveChanges();
                            var enrollments = new List<Enrollment>
                {
                new Enrollment{StudentID=1,CourseID=1050,Grade=Grade.A},
                new Enrollment{StudentID=1,CourseID=4022,Grade=Grade.C},
                new Enrollment{StudentID=1,CourseID=4041,Grade=Grade.B},
                new Enrollment{StudentID=2,CourseID=1045,Grade=Grade.B},
                new Enrollment{StudentID=2,CourseID=3141,Grade=Grade.F},
                new Enrollment{StudentID=2,CourseID=2021,Grade=Grade.F},
                new Enrollment{StudentID=3,CourseID=1050},
                new Enrollment{StudentID=4,CourseID=1050,},
                new Enrollment{StudentID=4,CourseID=4022,Grade=Grade.F},
                new Enrollment{StudentID=5,CourseID=4041,Grade=Grade.C},
                new Enrollment{StudentID=6,CourseID=1045},
                new Enrollment{StudentID=7,CourseID=3141,Grade=Grade.A},
                };
                enrollments.ForEach(s => context.Enrollments.Add(s));
                context.SaveChanges();
            }
        }
    }

    Tuesday, June 19, 2018 7:52 PM

Answers

  • User1292113567 posted

    I figured it out. I'm dyslexic, and I couldn't see that my program and assembly were called "ConsotoUniversity", not "ContosoUniversity" (I still have a LOT of trouble seeing the difference between those words).

    So I would double check to see that my DLL was being built and yes, there was "ConsotoUniversity.dll"... which is not what it was looking for.

    Live and learn.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, June 21, 2018 6:17 PM

All replies

  • User1724605321 posted

    Hi EmilySmirle,

    Would you please show the application directory structure ? For example , my application name is "WebApplication1" ,SchoolContext and SchoolInitializer is in DAL folder of root project folder with namespace : WebApplication1.DAL . Then web.config will like :

     <contexts>
          <context type="WebApplication1.DAL.SchoolContext, WebApplication1">
            <databaseInitializer type="WebApplication1.DAL.SchoolInitializer, WebApplication1" />
          </context>
        </contexts>

     In addition , you set "Initial Catalog=ContosoUniversityData" in your connect string so database name will be "ContosoUniversityData" .

    Best Regards,

    Nan Yu

    Wednesday, June 20, 2018 8:46 AM
  • User1292113567 posted

    Hi Nan Yu;

    Here is my application directory structure:

    My application directory structure

    Here is my database 

    Here is my database

    Everything (as far as I can tell) seems to be set up correctly...

    Thursday, June 21, 2018 2:47 PM
  • User1292113567 posted

    The SchoolContext and SchoolInitializer are in 

    namespace ContosoUniversity.DAL

    Thursday, June 21, 2018 2:49 PM
  • User1292113567 posted

    I figured it out. I'm dyslexic, and I couldn't see that my program and assembly were called "ConsotoUniversity", not "ContosoUniversity" (I still have a LOT of trouble seeing the difference between those words).

    So I would double check to see that my DLL was being built and yes, there was "ConsotoUniversity.dll"... which is not what it was looking for.

    Live and learn.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, June 21, 2018 6:17 PM