Entity Framework Code-first: Seed Data

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.