錯誤:`DbMigrationsConfiguration
public class Configuration : DbMigrationsConfiguration // 正確指定 TContext
{
protected override void Seed(MvcDemoEntities context) // ❌ 缺少泛型參數聲明
{
// ...
}
}
public class Configuration : DbMigrationsConfiguration
{
// ✅ 方法簽名必須匹配基類:Seed(TContext context)
protected override void Seed(MvcDemoEntities context)
{
context.SysControllers.AddOrUpdate(
c => c.ControllerDisplayName, // 唯一鍵避免重複種子
new SysController { ControllerDisplayName = "abcd" },
new SysController { ControllerDisplayName = "asdaf" }
// ...
);
context.SaveChanges(); // 顯式保存
}
}
Database.SetInitializer(new MigrateDatabaseToLatestVersion());
替代原 `SetInitializer(new Configuration())`,確保自動遷移到最新版本再執行 Seed。internal sealed class Configuration : DbMigrationsConfiguration
{
public Configuration()
{
AutomaticMigrationsEnabled = true; // 開發環境建議開啟
AutomaticMigrationDataLossAllowed = false; // 生產嚴禁
ContextKey = "MyApp.Models.MyDbContext";
}
protected override void Seed(MyDbContext context)
{
// 1. 字典/枚舉數據
context.DictItems.AddOrUpdate(d => d.Code,
new DictItem { Code = "GENDER", Value = "Male" },
new DictItem { Code = "GENDER", Value = "Female" }
);
// 2. 管理員賬號
context.Users.AddOrUpdate(u => u.UserName,
new User { UserName = "admin", PasswordHash = Hash("123456"), Role = "Admin" }
);
context.SaveChanges();
}
}