首页 > 代码库 > EF Code-First 学习之旅 数据库初始化
EF Code-First 学习之旅 数据库初始化
1。CreateDatabaseIfNotExists:
2.DropCreateDatabaseIfModelChanges:
3.DropCreateDatabaseAlways:
4.Custom DB Initializer:
public class SchoolDBContext: DbContext { public SchoolDBContext(): base("SchoolDBConnectionString") { Database.SetInitializer<SchoolDBContext>(new CreateDatabaseIfNotExists<SchoolDBContext>()); //Database.SetInitializer<SchoolDBContext>(new DropCreateDatabaseIfModelChanges<SchoolDBContext>()); //Database.SetInitializer<SchoolDBContext>(new DropCreateDatabaseAlways<SchoolDBContext>()); //Database.SetInitializer<SchoolDBContext>(new SchoolDBInitializer()); } public DbSet<Student> Students { get; set; } public DbSet<Standard> Standards { get; set; } }
public class SchoolDBInitializer : CreateDatabaseIfNotExists<SchoolDBContext> { protected override void Seed(SchoolDBContext context) { base.Seed(context); } }
配置文件中初始化
<?xml version="1.0" encoding="utf-8" ?> <configuration> <appSettings> <add key="DatabaseInitializerForType SchoolDataLayer.SchoolDBContext, SchoolDataLayer" value="System.Data.Entity.DropCreateDatabaseAlways`1[[SchoolDataLayer.SchoolDBContext, SchoolDataLayer]], EntityFramework" /> </appSettings> </configuration>
<?xml version="1.0" encoding="utf-8" ?> <configuration> <appSettings> <add key="DatabaseInitializerForType SchoolDataLayer.SchoolDBContext, SchoolDataLayer" value="SchoolDataLayer.SchoolDBInitializer, SchoolDataLayer" /> </appSettings> </configuration>
关闭数据库初始化功能
public class SchoolDBContext: DbContext { public SchoolDBContext() : base("SchoolDBConnectionString") { //Disable initializer Database.SetInitializer<SchoolDBContext>(null); } public DbSet<Student> Students { get; set; } public DbSet<Standard> Standards { get; set; } }
<?xml version="1.0" encoding="utf-8" ?> <configuration> <appSettings> <add key="DatabaseInitializerForType SchoolDataLayer.SchoolDBContext, SchoolDataLayer" value="Disabled" /> </appSettings> </configuration>
初始化 种子 数据
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); } }
EF Code-First 学习之旅 数据库初始化
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。