在使用 EF的code fist 方法我们可能会用到这三个类型对象DropCreateDatabaseAlways(总是删除创建对象) DropCreateDatabaseIfModelChanges(如果对象盖面删除创建对象) CreateDatabaseIfNotExists(如果对象不存在删除创建对象)
今天就利用泛型和工厂模式,将这三个对象封装以下,首先对三个对象类型分别创建子类,便于后期扩展。
public class MyDropCreateDatabaseAlways<T> : DropCreateDatabaseAlways<T> where T : DbContext { } public class MyDropCreateDatabaseIfModelChanges<T> : DropCreateDatabaseIfModelChanges<T> where T : DbContext { } public class MyCreateDatabaseIfNotExists<T> : CreateDatabaseIfNotExists<T> where T : DbContext { }
对象扩展子类
在创建一个枚举类型方便调用
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); } }
调用示例
时间: 2024-10-13 20:22:05