反射:父类定义子类泛型方法

1、EF关闭自动检测

Database.SetInitializer<EFDBContext>(null);

2、父类BaseDBContext

    public class BaseDBContext : DbContext
    {
        public BaseDBContext(string strConn = "name=KTStoreModelConn")
            : base(strConn)
        {
            InitDB();
        }

        protected virtual void InitDB()
        {
            var method = typeof(Database).GetMethod("SetInitializer");
            method = method.MakeGenericMethod(this.GetType());
            method.Invoke(null, new object[] { null });
        }

        public DbSet<Product> Product { get; set; }
    }

其中InitDB就相当于

Database.SetInitializer<BaseDBContext>(null);

但是如果这样写的话,子类也要重写

    public class KTStoreModel : BaseDBContext
    {
        public KTStoreModel()
            :base("name=KTStoreModelConn")
        {
        }

        protected override void InitDB()
        {
            Database.SetInitializer<KTStoreModel>(null);
        }
    }

但是通过

            var method = typeof(Database).GetMethod("SetInitializer");
            method = method.MakeGenericMethod(this.GetType());
            method.Invoke(null, new object[] { null });

子类就可以不写

Database.SetInitializer<KTStoreModel>(null);

 3、性能:

        static void Main(string[] args)
        {
            Watcher(() =>
            {
                for (int i = 0; i < 1000000; i++)
                {
                    KTStoreModel model = new KTStoreModel();
                }
            });
            Watcher(() =>
            {
                for (int i = 0; i < 1000000; i++)
                {
                    KTStoreModel model = new KTStoreModel();
                }
            });
            Watcher(() =>
            {
                for (int i = 0; i < 1000000; i++)
                {
                    BaseDBContext model = new BaseDBContext();
                }
            });
            Watcher(() =>
            {
                for (int i = 0; i < 1000000; i++)
                {
                    BaseDBContext model = new BaseDBContext();
                }
            });
            Console.Read();
        }

        static void Watcher(Action action)
        {
            var watch = new Stopwatch();
            watch.Start();
            action();
            watch.Stop();
            Console.WriteLine(watch.ElapsedMilliseconds);
        }
View Code

 

 发射方法会慢一点点

posted @ 2022-02-28 14:02  江境纣州  阅读(45)  评论(0编辑  收藏  举报