Seeds for entities not working
I have this in 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" />
Launching the Global.asax application
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 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 to 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 seed of the initializer is still
Database is created, but ROWS is not added.
source to share
The initializer is never called unless you have access to the database. If you want to create a DB when the application starts calling a method Initialize
in your Global.asax:
context.Database.Initialize(true)();
Update 1:
The problem is you are setting the initializer on a different instance Database
, try this:
using (var db = new AppDataContext())
{
db.Database.SetInitializer(new AppDataContextInitializer());
db.Database.Initialize(true);
}
Or set the Initializer in the constructor DbContext
:
public AppDataContext()
{
Database.SetInitializer(new AppDataContextInitializer());
}
source to share