Entity Framework Code-First(19):Seed Data
2016-07-05 17:14
387 查看
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; } }
相关文章推荐
- JS正则表达式 替换括号,尖括号等
- 14.10.5 Reclaiming Disk Space with TRUNCATE TABLE 回收空间使用TRUNCATE TABLE
- 14.10.5 Reclaiming Disk Space with TRUNCATE TABLE 回收空间使用TRUNCATE TABLE
- Apache DbUtils 探秘
- 利用缓冲区溢出来执行函数
- lua遍历table
- 【待重置】记忆化搜索思想
- webService三要素 SOAP、WSDL、UDDI
- 新生练习1(递推)
- 关于Java Final 修饰的局部变量,多线程可以访问
- Apache DbUtils 探秘
- 创建maven自定义archetype项目
- angularjs - 415 (Unsupported Media Type)
- Android 不同应用通过SharedPreference实现共享数据
- gulp自动添加版本号
- 3.3 DXC简介——HANA数据抽取和同步
- HDU 5710 Digit-Sum 数学杂题
- redis缓存数据需要指定缓存有效时间范围段的多个解决方案 Calendar+quartz
- eclipse最有用快捷键整理
- Go语言圣经(中文版)读书笔记