我在我的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>();
}
}
和module.cs
public class Module
{
[Key]
public int Id { get; set; }
public string ModuleName { get; set; }
public string FontAwesomeClass { get; set; }
}
但是我的数据库没有创建,我缺少什么?
更新1,我在global.asax
上添加了这个 AppInitializacionHandler.Initialize();
我创建了这个类:
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);
}
}
}
和初始化程序种子一样
已创建数据库,但未添加任何ROWS。
答案 0 :(得分:7)
如果您无法访问数据库,则永远不会调用初始化程序。如果要在应用程序开始调用Global.asax中的Initialize
方法时创建数据库:
context.Database.Initialize(true)();
问题是你是在另一个Database
实例中设置初始化程序,试试这个:
using (var db = new AppDataContext())
{
db.Database.SetInitializer(new AppDataContextInitializer());
db.Database.Initialize(true);
}
或者在DbContext
构造函数上设置初始值设定项:
public AppDataContext()
{
Database.SetInitializer(new AppDataContextInitializer());
}