示例#1
0
        public static List <string> GetTableList(System.Data.Entity.DbContext db)
        {
            var tableNames = db.Database.SqlQuery <string>("SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE' AND TABLE_NAME NOT LIKE '%Migration%' AND TABLE_NAME NOT LIKE 'AspNet%'").ToList();

            return(tableNames);

            var type = db.GetType();

            return(db.GetType().GetProperties()
                   .Where(x => x.PropertyType.Name == "DbSet`1")
                   .Select(x => x.Name).ToList());
        }
示例#2
0
        /// <summary>
        /// clones db context; requires the cloned ctx to implement a ctor that takes in 2 params (DbConnection conn and bool contextOwnsConnection);
        /// </summary>
        /// <param name="ctx"></param>
        /// <param name="contextOwnsConnection"></param>
        /// <returns></returns>
        public static System.Data.Entity.DbContext Clone(this System.Data.Entity.DbContext ctx, bool contextOwnsConnection = true)
        {
            //need to clone the connection too as have no idea how the connection has been provided to the ctx - directly, via conn str name as conn str, etc.
            var clonedConn = (DbConnection)Activator.CreateInstance(ctx.Database.Connection.GetType());

            clonedConn.ConnectionString = ctx.Database.Connection.ConnectionString;

            //this is where the ctx type is expected to provide a constructor that takes in DbConnection conn and bool contextOwnsConnection
            System.Data.Entity.DbContext clonedCtx = null;
            try
            {
                clonedCtx =
                    (System.Data.Entity.DbContext)Activator.CreateInstance(ctx.GetType(), new object[] { clonedConn, contextOwnsConnection });
            }
            catch
            {
                //ignore
            }

            if (clonedCtx == null)
            {
                try
                {
                    //ok looks, like ctx does not implement a (DbConnection conn and bool contextOwnsConnection) ctor
                    //need to mess a bit more.
                    //this time need to dig a bit deeper and get a conn str name

                    //set a read only conn prop now...
                    //looks like the
                    var internalCtx = ctx.GetType().GetProperty("InternalContext", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(ctx);
                    var connStrName = (string)internalCtx.GetType()
                                      .GetProperty("ConnectionStringName", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).GetValue(internalCtx);

                    //try to create a ctx with a conn str name
                    clonedCtx = (System.Data.Entity.DbContext)Activator.CreateInstance(ctx.GetType(), new object[] { connStrName });

                    //Note: should set the ctx owns connection, but totally not sure where to find it...
                }
                catch
                {
                    //ignore
                }
            }

            if (clonedCtx == null)
            {
                throw new InvalidOperationException("It was not possible to clone the db context.");
            }

            return(clonedCtx);
        }
示例#3
0
        /// <summary>
        /// 获取当前 实体数据模型 上下问中指定实体类型的数据库表映射关系。
        /// </summary>
        /// <param name="_this">实体数据上下文对象。</param>
        /// <param name="entityType">实体数据模型类型,对应当前数据库上下文中的一个表。</param>
        /// <returns>返回实体数据模型类型 <paramref name="entityType"/> 对应当前实体数据上下文对象中数据库的相应数据表的映射关系描述对象。</returns>
        public static EntityTable GetEntityTable(this System.Data.Entity.DbContext _this, Type entityType)
        {
            Check.NotNull(_this);
            Check.NotNull(entityType);
            Type thisType = _this.GetType();
            Dictionary <Type, EntityTable> dict = null;
            EntityTable table = null;

            lock (_entityTableCache)
            {
                if (!_entityTableCache.Value.TryGetValue(thisType, out dict))
                {
                    dict = new Dictionary <Type, EntityTable>();
                    _entityTableCache.Value.Add(thisType, dict);
                }
                if (!dict.TryGetValue(entityType, out table))
                {
                    table = GetEntityTables(_this).FirstOrDefault(t => t.EntityType == entityType);
                    if (table != null)
                    {
                        dict.Add(entityType, table);
                    }
                }
            }
            return(table);
        }
示例#4
0
        /// <summary>
        /// 获取当前 实体数据模型 上下文中定义的所有 实体数据模型 类型所映射的数据表信息。
        /// </summary>
        /// <param name="_this">实体数据上下文对象。</param>
        /// <returns>返回当前 实体数据模型 上下文中定义的所有 实体数据模型 类型所映射的数据表信息。</returns>
        public static EntityTable[] GetEntityTables(this System.Data.Entity.DbContext _this)
        {
            Check.NotNull(_this);
            Type thisType = _this.GetType();

            EntityTable[] tables = null;
            lock (_entityTablesCache)
            {
                if (!_entityTablesCache.Value.TryGetValue(thisType, out tables))
                {
                    MetadataWorkspace    metadata   = GetMetadataWorkspace(_this);
                    ObjectItemCollection collection = metadata.GetItemCollection(DataSpace.OSpace) as ObjectItemCollection;

                    EntityContainer container = metadata.GetItems <EntityContainer>(DataSpace.CSpace).FirstOrDefault();
                    if (container == null)
                    {
                        throw new InvalidConstraintException("获取实体数据上下文对象中的 实体容器对象失败,无法获取其 EntityContainer。");
                    }

                    var entitySets        = container.EntitySets;
                    var entitySetMappings = metadata.GetItems <EntityContainerMapping>(DataSpace.CSSpace).FirstOrDefault().EntitySetMappings;
                    var entityTypes       = metadata.GetItems <EntityType>(DataSpace.OSpace);

                    List <EntityTable> list = new List <EntityTable>();
                    foreach (var entityType in entityTypes)
                    {
                        var elemType = collection.GetClrType(entityType);
                        if (elemType == null)
                        {
                            continue;
                        }

                        var entitySet       = entitySets.First(s => s.ElementType.Name == entityType.Name);
                        var mapping         = entitySetMappings.First(s => s.EntitySet == entitySet);
                        var mappingFragment = (mapping.EntityTypeMappings.FirstOrDefault(a => a.IsHierarchyMapping) ?? mapping.EntityTypeMappings.First()).Fragments.Single();

                        EntityTable table = new EntityTable();
                        table.ModelSet   = entitySet;
                        table.StoreSet   = mappingFragment.StoreEntitySet;
                        table.ModelType  = entityType;
                        table.StoreType  = mappingFragment.StoreEntitySet.ElementType;
                        table.EntityType = elemType;
                        table.TableName  = entitySet.GetTableName();
                        table.Schema     = entitySet.Schema;
                        list.Add(table);
                    }
                    tables = list.ToArray();
                    _entityTablesCache.Value.Add(thisType, tables);
                }
            }
            return(tables);
        }
示例#5
0
        /// <summary>
        /// 获取当前 实体数据库上下文对象 所示类型中定义的所有 <see cref="DbSet&lt;TEntity&gt;"/> 数据集合属性。
        /// </summary>
        /// <param name="_this">表示一个 实体数据库上下文对象。</param>
        /// <param name="onlyReturnGenericDbSet">一个布尔类型值,表示该方法返回的结果中是否仅包含泛型类型的 <see cref="DbSet{TEntity}"/> 属性定义,该值默认为 true。</param>
        /// <returns>返回 <paramref name="_this"/> 所示的 实体数据库上下文 对象类型中定义的所有 <see cref="DbSet&lt;TEntity&gt;"/> 数据集合属性。</returns>
        public static PropertyInfo[] GetSetProperties(this System.Data.Entity.DbContext _this, bool onlyReturnGenericDbSet = false)
        {
            Check.NotNull(_this);
            Type dbSetType        = typeof(DbSet);
            Type genericDbSetType = typeof(DbSet <>);
            var  properties       = from property in _this.GetType().GetProperties()
                                    let type = property.PropertyType
                                               where onlyReturnGenericDbSet
                                ? genericDbSetType.IsAssignableFrom(type.IsGenericType?type.GetGenericTypeDefinition() : type)
                                : dbSetType.IsAssignableFrom(type) || genericDbSetType.IsAssignableFrom(type.IsGenericType ? type.GetGenericTypeDefinition() : type)
                                               select property;

            return(properties.ToArray());
        }
示例#6
0
        public static List <PropertyInfo> GetDbSetProperties(this System.Data.Entity.DbContext context)
        {
            var dbSetProperties = new List <PropertyInfo>();
            var properties      = context.GetType().GetProperties();

            foreach (var property in properties)
            {
                var setType = property.PropertyType;

                var isDbSet = setType.IsGenericType && (typeof(IDbSet <>).IsAssignableFrom(setType.GetGenericTypeDefinition()) || setType.GetInterface(typeof(IDbSet <>).FullName) != null);


                if (isDbSet)
                {
                    dbSetProperties.Add(property);
                }
            }

            return(dbSetProperties);
        }
        public CacheEntityContextBuilder(DbContext dbContext)
        {
            DbContext = dbContext;

            List <Type> types = new List <Type>();

            foreach (var property in DbContext.GetType().GetProperties())
            {
                if (!property.PropertyType.IsGenericType)
                {
                    continue;
                }
                if (property.PropertyType.GetGenericTypeDefinition() != typeof(DbSet <>))
                {
                    continue;
                }
                types.Add(property.PropertyType.GetGenericArguments()[0]);
            }
            EntityTypes = types.ToArray();
        }
示例#8
0
        /// <summary>
        /// 获取当前 实体数据上下文 对象中定义的所有实体集合信息。
        /// </summary>
        /// <param name="_this">实体数据上下文 对象。</param>
        /// <returns>返回当前 实体数据上下文 对象中定义的所有实体集合信息。</returns>
        public static EntitySet[] GetEntitySets(this System.Data.Entity.DbContext _this)
        {
            Check.NotNull(_this);
            Type thisType = _this.GetType();

            EntitySet[] sets = null;
            lock (_entitySetsCache)
            {
                if (!_entitySetsCache.Value.TryGetValue(thisType, out sets))
                {
                    MetadataWorkspace metadata  = GetMetadataWorkspace(_this);
                    EntityContainer   container = metadata.GetItems <EntityContainer>(DataSpace.SSpace).FirstOrDefault();
                    if (container == null)
                    {
                        throw new InvalidConstraintException("获取实体数据上下文对象中的 实体容器对象失败,无法获取其 EntityContainer。");
                    }
                    sets = container.EntitySets.ToArray();
                    _entitySetsCache.Value.Add(thisType, sets);
                }
            }
            return(sets);
        }