Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Seed Database at Application Start - ASP MVC 3 and EF

For some reason I cannot get my application to seed the database with some test data when the application starts up.

Order of execution:

     1) Application_Start() in Global.asax

         - Database.SetInitializer<LocatorContext>(new DropCreateDatabaseAlways<LocatorContext>());

         - new LocatorContext.DropCreateIfChangeInitializer()
           .InitializeDatabase(new LocatorContext());

     2) onModelCreating() in my DBContext class 


     3) Page is rendered and no data is inserted into the database

Any thoughts as to why or how I can fix it would be much appreciated.

My Global.asax.cs File

//Global.asax.cs
protected void Application_Start()
{
    Database.SetInitializer<LocatorContext>(new DropCreateDatabaseAlways<LocatorContext>());

    AreaRegistration.RegisterAllAreas();
    RegisterGlobalFilters(GlobalFilters.Filters);
    RegisterRoutes(RouteTable.Routes);
}

My DBContext Class

//ClubLocatorContext.cs        
using System;
using System.Collections.Generic;
using System.Data.Entity.ModelConfiguration.Conventions;
using System.Linq;
using System.Web;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using ClubLocator.Models;
using ClubLocator.Models.ViewModels;

namespace ClubLocator.DAL
{
    public class LocatorContext : DbContext
    {

      public DbSet<Prospect> Prospects { get; set; }

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

      public void Seed(LocatorContext context)
      {
          var prospect = new List<Prospect>
                         {
                              new Prospect
                              {
                                      FirstName = "John",
                                      LastName = "Smith",
                                      Address1 = "1313 Mockingbird Lane",
                                      Email = "[email protected]"
                              }
                         };

          prospect.ForEach(r => context.Prospects.Add(r));
          context.SaveChanges();
      }

      public class DropCreateIfChangeInitializer : DropCreateDatabaseIfModelChanges<LocatorContext>
      {
          protected override void Seed(LocatorContext context)
          {
              context.Seed(context);
              base.Seed(context);
          }
      }

      public class CreateInitializer : DropCreateDatabaseAlways<LocatorContext>
      {
          protected override void Seed(LocatorContext context)
          {
              context.Seed(context);
              base.Seed(context);
          }
      }

      static LocatorContext()
      { 
          #if DEBUG
          Database.SetInitializer<LocatorContext> (new DropCreateIfChangeInitializer ());
          #else
          Database.SetInitializer<LocatorContext> (new CreateInitializer ());
          #endif
      }
    }
}
like image 513
Slinky Avatar asked Jan 14 '23 02:01

Slinky


1 Answers

First off, all your EF code looks fine.

The problem is, you have initialize your database. Otherwise EF will wait until you access it in some way to initialize it.

You could navigate your website as much as you want without the database even starting up, if none of the pages access the data.

If you want to force the database to initialize when the application starts, do something like this:

using (var db = new LocatorContext())
{
    db.Database.Initialize(true);
}

I usually i create a static class like:

public static class LocatorInitializationHandler
{
    public static void Initialize()
    {
        // if you want to use your initializer
        Database.SetInitializer(new CreateInitializer()); 

        using (var db = new LocatorContext())
        {
            db.Database.Initialize(true);
        }
    }
}

Which i can then call from App_start:

//Global.asax.cs
protected void Application_Start()
{
    LocatorInitializationHandler.Initialize();

    AreaRegistration.RegisterAllAreas();
    RegisterGlobalFilters(GlobalFilters.Filters);
    RegisterRoutes(RouteTable.Routes);
}
like image 105
Jim Wolff Avatar answered Jan 21 '23 07:01

Jim Wolff