时间:2021-07-01 10:21:17 帮助过:2人阅读
在创建一个枚举类型方便调用
public enum CreateDatabaseWayType { DropCreateDatabaseAlways = 1, DropCreateDatabaseIfModelChanges = 2, CreateDatabaseIfNotExists = 3, }枚举类型
最后是一个工厂模式
public static class CreateDatabaseFactory { public static IDatabaseInitializer<T> ChooseCreateDatabaseWay<T>(CreateDatabaseWayType createDatabaseWayType) where T : DbContext { switch (createDatabaseWayType) { case CreateDatabaseWayType.DropCreateDatabaseAlways: return new MyDropCreateDatabaseAlways<T>(); case CreateDatabaseWayType.DropCreateDatabaseIfModelChanges: return new MyDropCreateDatabaseIfModelChanges<T>(); case CreateDatabaseWayType.CreateDatabaseIfNotExists: default: return new MyCreateDatabaseIfNotExists<T>(); } } }工厂模式
调用示例
在上下文的构造函数中
public XHRTContext(bool init) : base("name=XHRT") { if (init) { SetInitializer(CreateDatabaseWay.ChooseCreateDatabasefactory<XHRTContext>(CreateDatabaseWayType.DropCreateDatabaseAlways)); Database.Initialize(true); } }调用示例
.Net利用泛型封装EF CodeFirst 数据库初始值设定项
标签: