Seed Database at Application Start - ASP MVC 3 and EF

徘徊边缘 提交于 2019-12-01 04:53:20

问题


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 = "jsmith@example.com"
                              }
                         };

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

回答1:


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


来源:https://stackoverflow.com/questions/17236716/seed-database-at-application-start-asp-mvc-3-and-ef

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!