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; }