Entity Framework Code - the first default data in the database

How do I handle situations in which I need pre-existing data before the application is launched or immediately after creating the database. For example, I have a list of countries in which I would like to load into the database after the first code generation. How to do it?

The application is structured as follows:

Repository > Service > WebMVC

xml is in the WebMVC project.

+44
initialization database entity-framework ef-code-first
Apr 13 2018-11-21T00:
source share
3 answers

A custom initializer is created that inherits the DropCreateDatabaseIfModelChanges or DropCreateDatabaseAlways . How:

 public class EntitiesContextInitializer : DropCreateDatabaseIfModelChanges<-YourDbContext-> 

And then you overwrite the Seed method, for example:

 protected override void Seed(YourDbContext context) 

The whole example might look like this:

 public class EntitiesContextInitializer : DropCreateDatabaseIfModelChanges<EntitiesContext> { protected override void Seed(EntitiesContext context) { List<Role> roles = new List<Role> { new Role {Id=1, Title="Admin"}, new Role {Id=2, Title="ProjectManager"}, new Role {Id=3, Title="Developer"} }; // add data into context and save to db foreach (Role r in roles) { context.Roles.Add(r); } context.SaveChanges(); } } 

Edit: after setting this parameter, you must also install the Initializer, as noted by Ladislav Mrnka.

 Database.SetInitializer(new EntitiesContextInitializer()); 

i.e. ..: in Global.asax:

 protected void Application_Start() { AreaRegistration.RegisterAllAreas(); RegisterGlobalFilters(GlobalFilters.Filters); RegisterRoutes(RouteTable.Routes); Database.SetInitializer(new EntitiesContextInitializer()); } 

Remember to add using System.Data.Entity; .....

+67
Apr 13 2018-11-21T00:
source share

You must create your own database initializer, obtained, for example, from DropCreateDatabaseIfModelChanges and fill in the data using the overriden Seed method. Then you should use Database.SetInitializer to install a new initializer at application startup. Here is an example (from CTP5) used to create a custom index in a database.

+10
Apr 13 2018-11-21T00:
source share

For an example, see the new MVC / Entity Framework tutorial series http://www.asp.net/entity-framework/tutorials#Using%20MVC Both # 1 and # 4 show initialization classes.

+1
Apr 13 2018-11-11T00:
source share



All Articles