首页 > 其他 > 详细

Entity Framework Code-First(19):Seed Data

时间:2016-07-05 18:35:16      阅读:209      评论:0      收藏:0      [点我收藏+]

Seed Database in Code-First:

You can insert data into your database tables during the database initialization process. This will be important if you want to provide some test data for your application or to provide some default master data for your application.

To seed data into your database, you have to create custom DB initializer, as you created in DB Initialization Strategy, and override the Seed method. The following example shows how you can provide default data for the Standard table while initializing the School database:

public class SchoolDBInitializer : DropCreateDatabaseAlways<SchoolDBContext>
{
    protected override void Seed(SchoolDBContext context)
    {
        IList<Standard> defaultStandards = new List<Standard>();

        defaultStandards.Add(new Standard() { StandardName = "Standard 1", Description = "First Standard" });
        defaultStandards.Add(new Standard() { StandardName = "Standard 2", Description = "Second Standard" });
        defaultStandards.Add(new Standard() { StandardName = "Standard 3", Description = "Third Standard" });

        foreach (Standard std in defaultStandards)
            context.Standards.Add(std);

        base.Seed(context);
    }
}

 

Now, set this DB initializer class in context class as below.

public class SchoolContext: DbContext 
{
        
    public SchoolContext(): base("SchoolDBConnectionString") 
    {
        Database.SetInitializer(new SchoolDBInitializer());

    }
    public DbSet<Student> Students { get; set; }
    public DbSet<Standard> Standards { get; set; }
}

 

Entity Framework Code-First(19):Seed Data

原文:http://www.cnblogs.com/purplefox2008/p/5644366.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!