MVC启动时填充表

本文关键字:填充 启动 MVC | 更新日期: 2023-09-27 18:24:53

我在MVC中使用CodeFirst方法。我有一个填满表格的代码,

db.Categories.Add(new CategoryViewModel { Title = "Metal" });
db.Categories.Add(new CategoryViewModel { Title = "Pop" }); //etc

有没有什么地方可以放这些代码,以便在应用程序启动时填满表格?而不是在我的控制器中被调用多次。

MVC启动时填充表

您可以创建一个自定义数据库初始值设定项,并重写Seed方法来对表进行自定义记录插入。

创建一个继承自DropCreateDatabaseIfModelChanges 的新类

public class MyNiceInitializer : DropCreateDatabaseIfModelChanges<MyDbContext>
{
    protected override void Seed(MyDbContext context)
    {
        var categoryList= new List<Category>();
        categoryList.Add(new Category() { Title= "Metal"});
        categoryList.Add(new Category() { Title= "Pop" });
        foreach (var category in categoryList)
            context.Categories.Add(category);
        base.Seed(context);
    }
}

现在,在您的DbContext类中,将我们创建的这个新的自定义初始值设定项的一个新实例传递给Database.SetInitializer方法。

public class MyDbContext : DbContext
{
    public MyDbContext() : base("YourEFConnStringName")
    {
        Database.SetInitializer<MyDbContext>(new MyNiceInitializer());
    }
    public DbSet<Category> Categories { set; get; }
    //Other Items goes here...
}

当您第一次运行应用程序并访问Dbcontext的任何DbSet属性时,EF将执行您的自定义初始值设定项的种子方法,我们将在其中插入一些记录。不会在每次运行应用程序/页面时都发生这种情况。

由于我们是从DropCreateDataBaseIfModelChanges继承的,所以每次更改模型(类)以及重新创建数据库时,都会进行种子设定。