Seed Database at Application Start - ASP MVC 3 and EF

前端 未结 1 1881
梦谈多话
梦谈多话 2021-01-13 19:08

For some reason I cannot get my application to seed the database with some test data when the application starts up.

Order of execution:

<         


        
1条回答
  •  一生所求
    2021-01-13 19:47

    First off, all your EF code looks fine.

    The problem is, you have initialize your database. Otherwise EF will wait until you access it in some way to initialize it.

    You could navigate your website as much as you want without the database even starting up, if none of the pages access the data.

    If you want to force the database to initialize when the application starts, do something like this:

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

    I usually i create a static class like:

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

    Which i can then call from App_start:

    //Global.asax.cs
    protected void Application_Start()
    {
        LocatorInitializationHandler.Initialize();
    
        AreaRegistration.RegisterAllAreas();
        RegisterGlobalFilters(GlobalFilters.Filters);
        RegisterRoutes(RouteTable.Routes);
    }
    

    0 讨论(0)
提交回复
热议问题