Search code examples
c#asp.net-mvcentity-frameworkasp.net-mvc-4initializer

ASP.NET MVC Initializer doesn't seed Database during Update-Database


The tagged duplicate question uses a custom context, I'm using the default ApplicationDbContext.

I'm confused why data isn't seeded whenever I run Update-Database. I read the other questions with answers but unfortunately they're using a custom Context, I'm using the default ApplicationDbContext. They seem to have the same answers but they don't work on my end.

I have the following done;

I have a custom Initializer:

public class PostInitializer : DropCreateDatabaseAlways<ApplicationDbContext>
{
        protected override void Seed(ApplicationDbContext db)
        {
            var posts = new List<Post>
            {
                new Post()
                {
                    Content = "TestA"
                },
                new Post()
                {
                    Content = "TestB"
                }
            };

            posts.ForEach(p => db.Posts.Add(p));
            db.SaveChanges();
        }
}

In My Global Asax:

public class MvcApplication : System.Web.HttpApplication
{
        protected void Application_Start()
        {
            // call PostInitializer here
            Database.SetInitializer(new PostInitializer());

            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
        }
}

My Model:

public class Post
{
     [Key]
     public int PostId { get; set; }
     public string Title { get; set; }
     public string Content { get; set; }
     public DateTime? DateTimeCreated { get; set; }
}

I've tried deleting the DB and running Update-Database after, however data still isn't seeded.


Solution

  • Ok my bad. What solved this was running the application. I thought the seeding would happen during Update-Database. This is what worked for me;

    1. Run App
    2. Access Controller with the Model concerned in Initializer, accessing at least the Index page worked for me (localhost/posts)
    3. During Access, the Database will be dropped and created, then seeded with whatever specified in the Initializer
    4. Close any SQL tabs on Visual Studio that is connected to the target DB as it might throw an error during Drop Database