/// <summary>
        /// 根据对象类型获取值
        /// </summary>
        /// <typeparam name="T">泛型对象</typeparam>
        /// <param name="entityType">泛型对象的类型,为了兼容以前的接口才这么做</param>
        /// <param name="transaction">事务</param>
        /// <param name="db">数据库对象</param>
        /// <param name="cmd">数据库命令</param>
        /// <returns>对象集合</returns>
        public List <T> GetObjects <T>(Type entityType, DbTransaction transaction, Database db, DbCommand cmd)
        {
            if (entityType.IsValueType || entityType.Equals(typeof(string)))
            {
                return(GetValueTypeObjects <T>(entityType, transaction, db, cmd));
            }

            bool isBaseModelSub = entityType.IsSubclassOf(typeof(BaseModel));
            var  attMapping     = MB.Orm.Mapping.AttMappingManager.Instance;
            var  lstMapping     = attMapping.CheckExistsModelMapping(entityType) ?
                                  attMapping.GetModelMappingInfo(entityType).FieldPropertys.Values.ToList() : attMapping.GetEntityMappingPropertys(entityType);

            List <T> ic = new List <T>();
            var      qh = _QueryBehavior;

            if (qh == null)
            {
                qh = MessageHeaderHelper.GetQueryBehavior();
            }
            resetDynamicColumns(cmd, qh);
            string cmdMsg = MB.Orm.Persistence.DbCommandExecuteTrack.Instance.CommandToTrackMessage(db, cmd);

            MB.Util.TraceEx.Write("正在执行:" + cmdMsg);
            using (new Util.MethodTraceWithTime(true, cmdMsg))
            {
                using (IDataReader reader = transaction == null ? db.ExecuteReader(cmd) : db.ExecuteReader(cmd, transaction))
                {
                    try
                    {
                        DataTable dtReader = reader.GetSchemaTable();
                        Dictionary <string, MB.Util.Emit.DynamicPropertyAccessor> existsFields = new Dictionary <string, MB.Util.Emit.DynamicPropertyAccessor>();
                        foreach (MB.Orm.Mapping.FieldPropertyInfo proInfo in lstMapping)
                        {
                            if (dtReader.Select(string.Format("ColumnName='{0}'", proInfo.FieldName)).Length <= 0)
                            {
                                continue;
                            }
                            System.Reflection.PropertyInfo propertyInfo = entityType.GetProperty(proInfo.PropertyName);
                            if (propertyInfo == null)
                            {
                                continue;
                            }

                            MB.Util.Emit.DynamicPropertyAccessor propertyAccess = new MB.Util.Emit.DynamicPropertyAccessor(entityType, propertyInfo);
                            existsFields.Add(proInfo.FieldName, propertyAccess);
                        }
                        if (existsFields.Count > 0)
                        {
                            int rows       = -1;
                            int firstIndex = qh != null ? qh.PageIndex * qh.PageSize : -1;

                            while (reader.Read())
                            {
                                rows += 1;
                                //限制读取的最大行数
                                if (qh != null)
                                {
                                    if (rows < firstIndex)
                                    {
                                        continue;
                                    }
                                    if ((rows - firstIndex) >= qh.PageSize)
                                    {
                                        int currentRowsCount = rows - firstIndex;
                                        //如果读取的记录数大于当前页规定的记录数,如果要返回全部记录,则游标继续,如果不要返回,则推出循环
                                        if (qh.IsTotalPageDisplayed)
                                        {
                                            continue;
                                        }
                                        else if (currentRowsCount == qh.PageSize) //在服务器这边多读取一条,以通知客户端是否需要分页
                                        {
                                            continue;
                                        }
                                        else
                                        {
                                            break;
                                        }
                                    }
                                }

                                T entity = (T)MB.Util.DllFactory.Instance.CreateInstance(entityType);

                                foreach (var proInfo in existsFields)
                                {
                                    var val = reader[proInfo.Key];
                                    if (val != null && val != System.DBNull.Value)
                                    {
                                        existsFields[proInfo.Key].Set(entity, val);
                                    }
                                }
                                if (isBaseModelSub)
                                {
                                    MB.Orm.Common.BaseModel temp = entity as MB.Orm.Common.BaseModel;
                                    temp.EntityState = EntityState.Persistent;
                                }
                                ic.Add(entity);
                            }

                            if (qh != null && qh.PageSize < Int32.MaxValue)
                            {
                                //如果有些语句不想分页的,要么不设置QueryBehavior或者把PageSize设置为MaxValue,则不传分页信息到客户端
                                MessageHeaderHelper.AppendMessageHeaderResponse(new ResponseHeaderInfo(rows + 1), true);
                                DataBaseQueryResult.Instance.SetTotalRows(rows + 1);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        throw new MB.RuleBase.Exceptions.DatabaseExecuteException("执行GetObjectsByXml<" + entityType.FullName + "> 出错!", ex);
                    }
                    finally
                    {
                        cmd.Dispose();
                    }
                }
            }
            return(ic);
        }
Exemplo n.º 2
0
        /// <summary>
        /// 根据键值获取包含值的实体对象。
        /// </summary>
        /// <typeparam name="T">从MB.Orm.Common.BaseModel 中继承的数据对象类型。</typeparam>
        /// <param name="baseRule">获取实体对象集合的业务类。</param>
        /// <param name="dataInDocType">在业务类中的数据类型。</param>
        /// <param name="keyValue">需要获取实体键值。</param>
        /// <returns>返回指定类型的实体对象。</returns>
        public T GetObjectByKey <T>(IBaseRule baseRule, object dataInDocType, object keyValue)
        {
            ObjectDataMappingAttribute mappingAtt = AttributeConfigHelper.Instance.GetObjectDataMappingAttribute(dataInDocType);

            if (mappingAtt == null)
            {
                throw new MB.RuleBase.Exceptions.RequireConfigDataMappingException(dataInDocType);
            }

            Database db = MB.Orm.Persistence.DatabaseHelper.CreateDatabase();

            System.Data.Common.DbCommand[] cmds = MB.Orm.Persistence.PersistenceManagerHelper.NewInstance.CreateDbCommandByXml(db,
                                                                                                                               mappingAtt.MappingXmlFileName, MB.Orm.Mapping.Xml.XmlSqlMappingInfo.SQL_SELECT_BY_KEY, keyValue);

            if (cmds.Length != 1)
            {
                throw new MB.RuleBase.Exceptions.SelectSqlXmlConfigException(mappingAtt.MappingXmlFileName, MB.Orm.Mapping.Xml.XmlSqlMappingInfo.SQL_SELECT_BY_KEY);
            }

            System.Data.Common.DbCommand cmd = cmds[0];
            Type entityType = typeof(T);

            if (string.Compare(entityType.FullName, "System.Object", true) == 0)
            {
                if (mappingAtt.EntityType == null)
                {
                    throw new MB.Util.APPException("业务类:" + baseRule.GetType().FullName + " 中的:" +
                                                   dataInDocType.GetType() + " 的数据值:" + dataInDocType.ToString() +
                                                   " 在配置ObjectDataMapping时需要配置 EntityType", MB.Util.APPMessageType.SysErrInfo);
                }
                entityType = mappingAtt.EntityType;
            }
            bool isBaseModelSub = entityType.IsSubclassOf(typeof(BaseModel));

            MB.Orm.Mapping.ModelMappingInfo modelMapping = MB.Orm.Mapping.AttMappingManager.Instance.GetModelMappingInfo(entityType);
            object entity = MB.Util.DllFactory.Instance.CreateInstance(entityType);
            string cmdMsg = MB.Orm.Persistence.DbCommandExecuteTrack.Instance.CommandToTrackMessage(db, cmd);

            MB.Util.TraceEx.Write("正在执行:" + cmdMsg);
            using (new Util.MethodTraceWithTime(cmdMsg))
            {
                using (IDataReader reader = db.ExecuteReader(cmd))
                {
                    try
                    {
                        DataTable dtReader = reader.GetSchemaTable();
                        while (reader.Read())
                        {
                            foreach (MB.Orm.Mapping.FieldPropertyInfo proInfo in modelMapping.FieldPropertys.Values)
                            {
                                if (dtReader.Select(string.Format("ColumnName='{0}'", proInfo.FieldName)).Length <= 0)
                                {
                                    continue;
                                }
                                if (reader[proInfo.FieldName] != System.DBNull.Value)
                                {
                                    MB.Util.MyReflection.Instance.InvokePropertyForSet(entity, proInfo.PropertyName, reader[proInfo.FieldName]);
                                }
                            }
                            break;
                        }
                    }
                    catch (Exception ex)
                    {
                        throw new MB.RuleBase.Exceptions.DatabaseExecuteException("执行" + baseRule.GetType().FullName + "GetObjectByKey<T> 出错!", ex);
                    }
                    finally
                    {
                    }
                }
            }
            if (isBaseModelSub)
            {
                MB.Orm.Common.BaseModel temp = entity as MB.Orm.Common.BaseModel;
                //if (temp == null)
                //    throw new MB.Util.APPException(string.Format("所有的数据实体对象都必须从MB.Orm.Common.BaseModel 继承,请检查{0}", entity.GetType()));
                temp.EntityState = EntityState.Persistent;
            }
            return((T)entity);
        }