Database Initializer Seed Method not being called

Jul 30, 2014 at 1:06 AM
I've trying to generate a new database, but the database is not being updated/created, and the seed method is never called, even if i try to execute some method to access the database.
Anyone have an idea of what is missing to make it work?

I'm to post my code below:

Here is the global.asax code:
    void Application_Start(object sender, EventArgs e)
    {
        Database.SetInitializer(new MyDbInitializer());
        MyDbContext myDbContext = new MyDbContext();
        myDbContext.Database.Initialize(true);
    }
The initializer class:
public class MyDbInitializer: DropCreateDatabaseIfModelChanges<MyDbContext>
{
    protected override void Seed(MyDbContext context)
    {
        var persons= new List<Person>
        {
            new Person() {Active= true, Name= "Marcos"}
        };

        persons.ForEach(s => context.Persons.Add(s));
        context.SaveChanges();
    }
}
The context class
public class MyDbContext : DataContext
{
    static MyDbContext()
    {
        MyDbContext(null);
    }
    public MyDbContext()
        : base("MyDbContext")
    {

    }

    public DbSet<Person> Persons { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

        modelBuilder.Entity<Person>().Property(p => p.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
        modelBuilder.Configurations.Add(new PersonMap());
    }
}
The web.config file, EF settings:

<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework" >
  <parameters>
    <parameter value="v11.0" />
  </parameters>
</defaultConnectionFactory>
<providers>
  <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>
Coordinator
Aug 1, 2014 at 5:31 PM
There is plenty of documentation out there on how to get EF CodeFirst working, there are few command lines you need to run in the NuGet package manager console. However this topic is outside the scope of the framework.
Aug 1, 2014 at 6:22 PM
Hi Lelong,

I´ve found out where was the error.
on the global.asax, i needed to change the order of the things

from
    Database.SetInitializer(new MyDbInitializer());
    MyDbContext myDbContext = new MyDbContext();
    myDbContext.Database.Initialize(true);
to
    MyDbContext myDbContext = new MyDbContext();
    Database.SetInitializer(new MyDbInitializer());
    myDbContext.Database.Initialize(true);
Marked as answer by lelong37 on 8/1/2014 at 11:31 AM