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.
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;