Entity Framework Seed not working

2019-05-18 06:52发布

问题:

I have this on my web.config.

<add name="AppDataContext" connectionString="Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\AppDatabase.mdf;Initial Catalog=AppDatabase;Integrated Security=True" providerName="System.Data.SqlClient" />

Global.asax APplication Start

 Database.SetInitializer<AppDataContext>(new AppDataContextInitializer());

AppDataContextInitializer.cs

public class AppDataContextInitializer : System.Data.Entity.CreateDatabaseIfNotExists<AppDataContext>
    {
        protected override void Seed(AppDataContext context)
        {
            #region Seed Modules
            context.ModuleList.Add(new Module() { Id = 1, ModuleName = "Contabilidad", FontAwesomeClass = "ambulance" });
            context.ModuleList.Add(new Module() { Id = 2, ModuleName = "Recursos Humanos", FontAwesomeClass = "heartbeat" });
            context.ModuleList.Add(new Module() { Id = 3, ModuleName = "Inventario", FontAwesomeClass = "medkit" }); 
            #endregion


            base.Seed(context);
        }
    }

AppDataContext.cs

public class AppDataContext : DbContext
    {

        public AppDataContext(): base("AppDataContext")
        {
        }

        public DbSet<Module> ModuleList { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
        }
    }

and the module.cs

 public class Module
    {
        [Key]
        public int Id { get; set; }
        public string ModuleName { get; set; }
        public string FontAwesomeClass { get; set; }
    }

However my database is not created, what am I missing?

Update 1, I added this on the global.asax

 AppInitializacionHandler.Initialize();

I created this class:

public class AppInitializacionHandler
    {
        public static void Initialize()
        {
            Database.SetInitializer(new AppDataContextInitializer()); //if u want to use your initializer
            using (var db = new AppDataContext())
            {
                db.Database.Initialize(true);
            }
        }
    }

and the initializer seed is as before

Database is created but no ROWS are added.

回答1:

The Initializer is never called if you don't access to the DB. If you want to create the DB when the application start call the Initialize method in your Global.asax:

context.Database.Initialize(true)();

Update 1:

The problem is you are setting the Initializer in a different Database instance, try this:

using (var db = new AppDataContext())
{
   db.Database.SetInitializer(new AppDataContextInitializer());
   db.Database.Initialize(true);
}

Or set the Initializer on the DbContext constructor:

 public AppDataContext()
 {
    Database.SetInitializer(new AppDataContextInitializer());
 }