简体   繁体   中英

Create database in App_Start

I have an solution with 2 projects, one domain class and one webUI.

In the domain class I have 2 models, a db context and a databas initializer.

List.cs:

namespace Todo.Domain
{
    public class List
    {
        public int ListID { get; set; }
        public string Day { get; set; }
        public ICollection<Task> Tasks { get; set; }
    }
}

Task.cs:

namespace Todo.Domain
{
    public class Task
    {
        public int TaskID { get; set; }
        public int ListID { get; set; }
        public string TodoTask { get; set; }
    }
}

EFDbContext.cs:

namespace Todo.Domain
{
    public class EFDbContext : DbContext
    {
        public EFDbContext() : base("TodoList") { }

        public DbSet<List> Lists { get; set; }
        public DbSet<Task> Tasks { get; set; }


    }
}

Initializer:

namespace Todo.Domain
{
    public class TodoDbInit : System.Data.Entity.DropCreateDatabaseIfModelChanges<EFDbContext>
    {
        protected override void Seed(EFDbContext context)
        {
            var list = new List<List>
            {
                new List { Day="Måndag" }
            };
            list.ForEach(s => context.Lists.Add(s));
            context.SaveChanges();


            var task = new List<Task>
            {
                new Task { TodoTask="Fisk" }
            };

            task.ForEach(s => context.Tasks.Add(s));
            context.SaveChanges();
        }
    }
}

Now, when I start my application, I want the database to be created. I have placed a setInitializer Global.asax:

namespace Todo.WebUI
{
    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            Database.SetInitializer(new TodoDbInit());
            AreaRegistration.RegisterAllAreas();
            RouteConfig.RegisterRoutes(RouteTable.Routes);
        }
    }
}

When I run my application, the database Is not created. I don't know why. Have I done something wrong?

You must make a call against your database in one of your controllers in order for it to be created (creation is on-demand). If you wish to manually create the database on application start see the answer posted here: Entity Framework code first, isn't creating the database

The following code is only setting the initializer that you wish to use against your database.

Database.SetInitializer(new TodoDbInit());

In order for it to actually be used you will need to create and access entities of your db context.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM