应用程序启动时的种子数据库 - ASP MVC 3和EF

时间:2013-06-21 13:38:48

标签: c# asp.net-mvc-3 entity-framework-5

出于某种原因,我无法让我的应用程序在应用程序启动时使用一些测试数据为数据库播种。

执行顺序:

     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

对于为什么或如何解决这个问题的任何想法都将非常感激。

我的Global.asax.cs文件

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

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

我的DBContext类

//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 个答案:

答案 0 :(得分:8)

首先,所有EF代码看起来都很好。

问题是,您已初始化数据库。否则EF将等到你以某种方式访问​​它以初始化它。

如果没有任何网页访问数据,您可以根据需要随意浏览您的网站,而不启动数据库。

如果要在应用程序启动时强制数据库初始化,请执行以下操作:

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

我通常会创建一个静态类,如:

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

然后我可以从App_start调用:

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

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