ASP.NET MVC 3 - DBContext类未执行

时间:2013-06-20 22:36:52

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

当我启动应用程序时,我正试图通过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
      }
    }
}

1 个答案:

答案 0 :(得分:1)

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