2014-05-19 46 views
0

我正在使用EF 6編寫一個新的MVC 5 Web API應用程序,其中第一個代碼在VS2012中。我的種子()方法永遠不會在Code First中調用EF 6

當我運行應用程序並查詢上下文時,新數據庫被創建,但種子覆蓋似乎沒有被調用。我有一個突破點是從不打:

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.Data.Entity; 

namespace MyAPI.Models 
{ 
    public class MyAPIContextInitializer : DropCreateDatabaseAlways<MyAPIContext> 
    { 
     protected override void Seed(MyAPIContext context) 
     { 
      var userAccounts = new List<UserAccount> 
      { 
       new UserAccount() { AccountActivated = true, AccountEnabled = true, AccountLocked = false, FailedLoginAttempts = 0, FirstName = "Jane", LastName = "Doe", 
       EmailAddress = "[email protected]", Password = "password", Username = "jane" }, 
       new UserAccount() { AccountActivated = true, AccountEnabled = true, AccountLocked = false, FailedLoginAttempts = 0, FirstName = "John", LastName = "Doe", 
       EmailAddress = "[email protected]", Password = "password", Username = "john" } 
      }; 

      foreach (var u in userAccounts) 
       context.UserAccounts.Add(u); 

      context.SaveChanges(); 

      base.Seed(context); 
     } 
    } 
} 

的Global.asax.cs:

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.Web.Http; 
using System.Web.Mvc; 
using System.Web.Optimization; 
using System.Web.Routing; 

namespace MyAPI 
{ 
    public class WebApiApplication : System.Web.HttpApplication 
    { 
     protected void Application_Start() 
     { 
      System.Data.Entity.Database.SetInitializer(new System.Data.Entity.DropCreateDatabaseAlways<MyAPI.Models.MyAPIContext>()); 

      AreaRegistration.RegisterAllAreas(); 

      WebApiConfig.Register(GlobalConfiguration.Configuration); 
      FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); 
      RouteConfig.RegisterRoutes(RouteTable.Routes); 
      BundleConfig.RegisterBundles(BundleTable.Bundles); 
     } 
    } 
} 

感謝您的幫助。

回答

0

嘗試

System.Data.Entity.Database.SetInitializer<MyAPIContext>(new MyAPIContextInitializer()); 

,並確保到數據庫進行呼叫。形成您的global.asax沒有電話進行。所以EF沒有理由初始化數據庫。

+0

看起來工作!不喜歡我無法在DropCreateDatabaseAlways和DropCreateDatabaseIfModelChanges之間輕鬆切換。但它有效,所以我不能抱怨太多。 (注意:正如我的文章所述,我正在調用數據庫/實體,因此它正在創建。) – ginalster

相關問題