ASP.NET MVC 4

MVC 5: Database Seeding

In the code first approach the database is created automatically from the fefined classes in the Models folder, this includes the membership database used to store user names and passwords. However when the models changes it is necessary to change the database to match

In MVC5 this is achieved by enabling database migrations. Open the Package Manager Console window using the Tools menu. Enter "enable-migrations" at the PM> command prompt. This will create a Migrations folder with a Configuration.cs class

Configuration.cs

In this class migrations can be enabled automatically, and by altering the seed method users and roles can be automatically added to the newly created database after alterations. The database cab be manually updated by entering the command "update-database" at the PM> command prompt in the Package Manage Console window.

Db Seeding

MVC 4: Database Seeding

The code first approach outlined here creates and re-creates a database from your C# Model classes. The down side is that each time the model is changed all the data is lost. To re-populate the database when it is recreated you need to add a ProjectInitializer class to your models folder. Click on the link and save the text file as ProjectInitializer.cs. Make sure you change the name of the project in the namespace to match your project name.

In order to use this class, you need to modify your global.asax and create a new ProjectInitializer when your application starts (and if the model changes). Change it to something like:-

Seeding

Please make sure that your project name is used in place of mvc4WebApplication, and the name of the class is not important you can spell it the british way ProjectInitialiser if you wish. Take out the old statement shown below.

Old Statement

  • Contoso University: Part 5 this example shows two ways of seeding the database using data migrations or drop and re-create the database on change.

MVC Index