我的Seed()方法永远不会在Code First EF 6中调用

时间:2014-05-19 08:23:08

标签: entity-framework asp.net-web-api

我正在使用EF 6编写一个新的MVC 5 Web API应用程序,其代码首先在VS2012中。

当我运行应用程序并查询上下文时,会创建新数据库,但种子覆盖似乎没有被调用。我有一个永远不会被击中的断点:

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 = "jane@yahoo.com", Password = "password", Username = "jane" },
                new UserAccount () { AccountActivated = true, AccountEnabled = true, AccountLocked = false, FailedLoginAttempts = 0, FirstName = "John", LastName = "Doe",
                 EmailAddress = "john@gmail.com", 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);
         }
     }
 }

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

尝试

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

确保调用db。形成你的global.asax没有打电话。所以EF没有理由初始化db。