EF获取DbContext中已注册的所有实体类型

        /// <summary>
        /// 获取DbContext中已注册的实体类型
        /// </summary>
        /// <typeparam name="T">DbContext上下文类型</typeparam>
        /// <param name="ass">实体所在程序集</param>
        /// <returns></returns>
        public IEnumerable<Type> GetEntityTypes<T>(Assembly ass) where T : DbContext, new()
        {
            var contextType = typeof(T);
            if (contextType != null)
            {
                var contextObj = new T();
                var objectContext = ((IObjectContextAdapter)contextObj).ObjectContext;
                var mdw = objectContext.MetadataWorkspace;
                var items = mdw.GetItems<EntityType>(DataSpace.OSpace);
                return
                    items
                      .Select(e => e.FullName)
                      .Distinct()
                      .Select(ass.GetType);
            }
            return null;
        }

 

posted @ 2017-05-06 15:57  谷草`  阅读(2149)  评论(0编辑  收藏  举报