实体框架种子不工作

本文关键字:工作 种子 框架 实体 | 更新日期: 2023-09-27 17:50:56

我有这个在我的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" />

全球。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>();
        }
    }

和模块。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);
            }
        }
    }

,初始化项seed和前面一样

数据库已创建,但未添加行

实体框架种子不工作

如果不访问DB,则永远不会调用Initializer。如果您想在应用程序启动时创建DB,请调用Global.asax:

中的Initialize方法。
context.Database.Initialize(true)();
更新1:

问题是你在不同的Database实例中设置初始化器,试试这个:

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

或者在DbContext构造函数上设置初始化式:

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