Seed Database in Code-first:
You can insert data into your database tables during the database initialization process. This'll be important if want to provide some test data for your application or to provide some default master data F or your application.
To seed data into your database, you have to create a custom DB initializer, as you created in DB initialization Strateg Y, and override the Seed method. The following example shows how can provide default data for the standard table while initializing the School database :
Public classSchooldbinitializer:dropcreatedatabasealways<schooldbcontext>{ protected Override voidSeed (Schooldbcontext context) {IList<Standard> defaultstandards =NewList<standard>(); Defaultstandards.add (NewStandard () {StandardName ="Standard 1", Description =" First Standard" }); Defaultstandards.add (NewStandard () {StandardName ="Standard 2", Description ="Second Standard" }); Defaultstandards.add (NewStandard () {StandardName ="Standard 3", Description ="Third Standard" }); foreach(Standard STDinchdefaultstandards) context. Standards.add (STD); Base. Seed (context); }}
Now, set the this DB initializer class in context class as below.
Public classSchoolcontext:dbcontext { PublicSchoolcontext ():Base("schooldbconnectionstring") {Database.setinitializer (NewSchooldbinitializer ()); } PublicDbset<student> Students {Get;Set; } PublicDbset<standard> Standards {Get;Set; }}
Entity Framework code-first: Seed Data