Martin Dawson
Martin Dawson

Reputation: 7656

MVC Filling a table on startup

I am using CodeFirst approach in MVC. I have code that fills up a table,

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

Is there some place I can put this code that will fill up the table on application startup? Instead of in my controllers that get called multiple times.

Upvotes: 0

Views: 1462

Answers (1)

Shyju
Shyju

Reputation: 218812

You can create a custom database initializer and override the Seed method to do your custom record insertions to your tables.

Create a new class inheriting from 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);
    }
}

Now in your DbContext class, Pass a new instance of this new custom initializer we created to Database.SetInitializer method.

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

When your run your app for the first time and accessing any of the DbSet properties of your Dbcontext, EF Will execute your Custom initializer's seed method where we are inserting some records. This will not happen every time you run your app/page.

Since we are inheriting from DropCreateDataBaseIfModelChanges, the seeding will happen every time you change your model(classes) along with the recreation of the db.

Upvotes: 1

Related Questions