zoukankan      html  css  js  c++  java
  • 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; }
    }
  • 相关阅读:
    (转)SQL Server 2005两种安全验证模式
    C#练习题记录(交换两个数1)
    C# using 用法
    服务器的理解(菜鸟)
    zZ
    ZzZ
    [转]Arcgis制作泰森多边形具体步骤
    [转]免费网站推广
    [转]如何让Firefox优化得比Chrome更快
    [转]3天搞定网站重新被百度收录的方法
  • 原文地址:https://www.cnblogs.com/purplefox2008/p/5644366.html
Copyright © 2011-2022 走看看