Entity Framework Code-First(19):Seed Data

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Entity Framework Code-First(19):Seed Data相关的知识,希望对你有一定的参考价值。

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的主要内容,如果未能解决你的问题,请参考以下文章

Entity Framework Code-First(23):Entity Framework Power Tools

Entity Framework怎么GroupBY多个字段

entity framework 公共类

Entity Framework Fluent API

初步了解Entity Framework

Entity Framework 中的in操作实例