1

当应用程序启动时,我试图通过 EF Code First 为我的应用程序提供一些测试数据。

这是我正在观察的:

当我运行应用程序时,执行进入:

Application_Start() {}

然后一旦在 Application_Start() 它登陆:

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

但它永远不会进入 DBContext 类 (ClubLocatorContext.cs),这是播种发生的地方,等等。

关于为什么或如何解决它的任何想法将不胜感激。

我的 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
      }
    }
}
4

1 回答 1

1
new DropCreateIfChangeInitializer()
                .InitializeDatabase(new LocatorContext());
于 2013-06-21T03:14:20.590 回答