Ejemplo n.º 1
0
        /// <summary>
        ///  根据OQL查询数据获得DataReader。如果指定single=真,将执行优化的查询以获取单条记录
        /// </summary>
        /// <param name="oql">OQL表达式</param>
        /// <param name="db">当前数据库访问对象</param>
        /// <param name="factEntityType">实体类类型</param>
        /// <param name="single">是否只查询一条记录</param>
        /// <returns>DataReader</returns>
        public static IDataReader ExecuteDataReader(OQL oql, AdoHelper db, Type factEntityType, bool single)
        {
            string sql = "";
            Dictionary <string, object> Parameters = null;

            //处理用户查询映射的实体类
            if (oql.EntityMap == PWMIS.Common.EntityMapType.SqlMap)
            {
                if (CommonUtil.CacheEntityMapSql == null)
                {
                    CommonUtil.CacheEntityMapSql = new Dictionary <string, string>();
                }
                if (!CommonUtil.CacheEntityMapSql.ContainsKey(oql.sql_table))
                {
                    string tempView = GetMapSql(factEntityType);
                    CommonUtil.CacheEntityMapSql.Add(oql.sql_table, tempView);
                }
                sql = oql.GetMapSQL(CommonUtil.CacheEntityMapSql[oql.sql_table]);


                //如果用户本身没有初始化参数对象,则这里声明一个 edit at 2012.11.16
                Parameters = oql.InitParameters ?? new Dictionary <string, object>();
                if (oql.Parameters != null && oql.Parameters.Count > 0)
                {
                    foreach (string name in oql.Parameters.Keys)
                    {
                        Parameters.Add(name, oql.Parameters[name]);
                    }
                }
            }
            else if (oql.EntityMap == PWMIS.Common.EntityMapType.StoredProcedure)
            {
                string script = "";
                if (CommonUtil.CacheEntityMapSql == null)
                {
                    CommonUtil.CacheEntityMapSql = new Dictionary <string, string>();
                }
                //获取SQL-MAP脚本
                if (CommonUtil.CacheEntityMapSql.ContainsKey(oql.sql_table))
                {
                    script = CommonUtil.CacheEntityMapSql[oql.sql_table];
                }
                else
                {
                    script = GetMapSql(factEntityType);
                    CommonUtil.CacheEntityMapSql.Add(oql.sql_table, script);
                }
                //对SQL-MAP格式的参数进行解析
                SqlMap.SqlMapper mapper = new PWMIS.DataMap.SqlMap.SqlMapper();
                mapper.DataBase = db;
                //解析存储过程名称
                sql = mapper.FindWords(mapper.GetScriptInfo(script), 0, 255); //由于是存储过程,需要特殊处理,调用 FindWords方法
                //解析参数
                IDataParameter[] paras = mapper.GetParameters(script);
                if (oql.InitParameters != null && oql.InitParameters.Count > 0)
                {
                    try
                    {
                        foreach (IDataParameter para in paras)
                        {
                            string key = para.ParameterName.TrimStart(db.GetParameterChar.ToCharArray());
                            para.Value = oql.InitParameters[key];
                        }
                    }
                    catch (KeyNotFoundException exKey)
                    {
                        throw new KeyNotFoundException("'存储过程实体类'的初始化参数中没有找到指定的参数名,请检查参数定义和设置。", exKey);
                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }
                }
                else
                {
                    if (paras.Length > 0)
                    {
                        throw new Exception("当前'存储过程实体类'需要提供初始化参数,请设置OQL对象的InitParameters属性");
                    }
                }

                return(db.ExecuteDataReader(sql, CommandType.StoredProcedure, paras));
            }
            else
            {
                //edit at 2013-2-25 处理非SQLSERVER的参数名前缀问题
                if (db is SqlServer)
                {
                    sql = oql.ToString();
                }
                else
                {
                    sql = oql.ToString().Replace("@", db.GetParameterChar);
                }
                Parameters = oql.Parameters;
            }


            //处理实体类分页 2010.6.20
            if (oql.PageEnable && !single)
            {
                switch (db.CurrentDBMSType)
                {
                case PWMIS.Common.DBMSType.Access:
                case PWMIS.Common.DBMSType.SqlServer:
                case PWMIS.Common.DBMSType.SqlServerCe:
                    //如果含有Order By 子句,则不能使用主键分页
                    if (oql.HaveJoinOpt || sql.IndexOf("order by", StringComparison.OrdinalIgnoreCase) > 0)
                    {
                        sql = PWMIS.Common.SQLPage.MakeSQLStringByPage(PWMIS.Common.DBMSType.SqlServer, sql, "", oql.PageSize, oql.PageNumber, oql.PageWithAllRecordCount);
                    }
                    else
                    {
                        if (oql.PageOrderDesc)
                        {
                            sql = PWMIS.Common.SQLPage.GetDescPageSQLbyPrimaryKey(oql.PageNumber, oql.PageSize, oql.sql_fields, oql.sql_table, oql.PageField, oql.sql_condition);
                        }
                        else
                        {
                            sql = PWMIS.Common.SQLPage.GetAscPageSQLbyPrimaryKey(oql.PageNumber, oql.PageSize, oql.sql_fields, oql.sql_table, oql.PageField, oql.sql_condition);
                        }
                    }
                    break;

                //case PWMIS.Common.DBMSType.Oracle:
                //    sql = PWMIS.Common.SQLPage.MakeSQLStringByPage(PWMIS.Common.DBMSType.Oracle, sql, "", oql.PageSize, oql.PageNumber, oql.PageWithAllRecordCount);
                //    break ;
                //case PWMIS.Common.DBMSType.MySql:
                //case PWMIS.Common.DBMSType.SQLite:
                //    sql = PWMIS.Common.SQLPage.MakeSQLStringByPage(PWMIS.Common.DBMSType.MySql, sql, "", oql.PageSize, oql.PageNumber, oql.PageWithAllRecordCount);
                //    break;
                //case PWMIS.Common.DBMSType.PostgreSQL:
                //    sql = PWMIS.Common.SQLPage.MakeSQLStringByPage(PWMIS.Common.DBMSType.PostgreSQL, sql, "", oql.PageSize, oql.PageNumber, oql.PageWithAllRecordCount);
                //    break;
                default:
                    sql = PWMIS.Common.SQLPage.MakeSQLStringByPage(db.CurrentDBMSType, sql, "", oql.PageSize, oql.PageNumber, oql.PageWithAllRecordCount);
                    break;
                }
            }

            IDataReader reader = null;

            if (Parameters != null && Parameters.Count > 0)
            {
                int fieldCount         = Parameters.Count;
                IDataParameter[] paras = new IDataParameter[fieldCount];
                int index = 0;

                foreach (string name in Parameters.Keys)
                {
                    paras[index] = db.GetParameter(name, Parameters[name]);
                    //为字符串类型的参数指定长度 edit at 2012.4.23
                    if (paras[index].Value != null && paras[index].Value.GetType() == typeof(string))
                    {
                        string field = FindFieldNameInSql(sql, name, db.GetParameterChar);
                        ((IDbDataParameter)paras[index]).Size = EntityBase.GetStringFieldSize(oql.sql_table, field);
                    }
                    index++;
                }
                if (single)
                {
                    reader = db.ExecuteDataReaderWithSingleRow(sql, paras);
                }
                else
                {
                    reader = db.ExecuteDataReader(sql, CommandType.Text, paras);
                }
            }
            else
            {
                if (single)
                {
                    reader = db.ExecuteDataReaderWithSingleRow(sql);
                }
                else
                {
                    reader = db.ExecuteDataReader(sql);
                }
            }
            return(reader);
        }
Ejemplo n.º 2
0
        /// <summary>
        /// 将实体集合中的所有数据导入数据库,如果数据已经存在则修改(先删除再插入)否则直接插入。如果实体中的数据只包含部分字段的数据,请勿使用该方法。
        /// </summary>
        /// <param name="entityList">同一实体类集合</param>
        /// <param name="DB">数据访问对象实例</param>
        /// <returns>操作受影响的行数</returns>
        private int ImportDataInner(List <EntityBase> entityList, CommonDB DB)
        {
            //必须保证集合中的元素都是同一个类型
            if (entityList == null || entityList.Count == 0)
            {
                return(0);
            }

            EntityBase entity = entityList[0];

            if (entity.PrimaryKeys.Count == 0)
            {
                throw new Exception("EntityQuery Error:当前实体类未指定主键字段");
            }
            int fieldCount = entity.PropertyNames.Length;

            if (fieldCount == 0)
            {
                throw new Exception("EntityQuery Error:实体类属性字段数量为0");
            }

            string tableName = entity.TableName;

            for (int i = 1; i < entityList.Count; i++)
            {
                if (entityList[0].TableName != tableName)
                {
                    throw new Exception("当前实体类集合的元素类型不一致,对应的表是:" + entityList[0].TableName);
                }
            }
            //先将主键对应的记录删除,再插入
            #region 构造查询语句
            //构造Delete 语句:
            //IDataParameter[] paras_delete = new IDataParameter[entity.PrimaryKeys.Count ];
            //string sql_delte = "DELETE FROM " + entity.TableName + " WHERE ";
            //string values = "";
            //string condition = "";
            //int index = 0;

            //foreach (string key in entity.PrimaryKeys)
            //{
            //    string paraName = "@P" + index.ToString();
            //    condition += " AND " + key + "=" + paraName;
            //    paras_delete[index] = DB.GetParameter();
            //    paras_delete[index].ParameterName = paraName;
            //    index++;
            //}
            //sql_delte = sql_delte + values.TrimStart(',') + " " + condition.Substring(" AND ".Length);

            ////构造Insert语句
            //string sql_insert = "INSERT INTO " + entity.TableName;
            //string fields = "";

            //IDataParameter[] paras_insert = new IDataParameter[fieldCount];
            //index = 0;

            //List<string> targetFields = GetTargetFields(tableName, entity.PropertyNames, DB);

            //foreach (string field in targetFields)
            //{
            //    //if (entity.IdentityName != field)//由于是导入数据,不必理会自增列
            //    //{
            //        fields += "," + field;
            //        string paraName = "@P" + index.ToString();
            //        values += "," + paraName;
            //        paras_insert[index] = DB.GetParameter();
            //        paras_insert[index].ParameterName = paraName;
            //        index++;
            //    //}
            //}
            //sql_insert = sql_insert + "(" + fields.TrimStart(',') + ") VALUES (" + values.TrimStart(',') + ")";

            EntityCommand ec = new EntityCommand(entity, DB);
            ec.IdentityEnable = true;//导入数据,不考虑自增列问题
            ec.TargetFields   = GetTargetFields(tableName, entity.PropertyNames, DB).ToArray();

            string           sql_delte    = ec.DeleteCommand;
            IDataParameter[] paras_delete = ec.DeleteParameters;

            string           sql_insert   = ec.InsertCommand;
            IDataParameter[] paras_insert = ec.InsertParameters;

            #endregion

            int count = 0;

            foreach (EntityBase item in entityList)
            {
                //执行删除
                foreach (IDataParameter para in paras_delete)
                {
                    para.Value = item.PropertyList(para.SourceColumn);
                }
                count += DB.ExecuteNonQuery(sql_delte, CommandType.Text, paras_delete);
                //执行插入
                foreach (IDataParameter para in paras_insert)
                {
                    //if (entity.IdentityName != field)//由于是导入数据,不必理会自增列
                    //{
                    para.Value = item.PropertyList(para.SourceColumn);
                    //}
                }
                count += DB.ExecuteNonQuery(sql_insert, CommandType.Text, paras_insert);
            }

            return(count);
        }
Ejemplo n.º 3
0
        private int InsertOrUpdateInner(List <EntityBase> entityList, CommonDB DB)
        {
            //必须保证集合中的元素都是同一个类型
            if (entityList == null || entityList.Count == 0)
            {
                return(0);
            }

            EntityBase entity = entityList[0];

            if (entity.PrimaryKeys.Count == 0)
            {
                throw new Exception("EntityQuery Error:当前实体类未指定主键字段");
            }
            int fieldCount = entity.PropertyNames.Length;

            if (fieldCount == 0)
            {
                throw new Exception("EntityQuery Error:实体类属性字段数量为0");
            }

            //CommonDB DB = MyDB.GetDBHelper();
            //IDataParameter[] paras = new IDataParameter[fieldCount];
            //string sql = "UPDATE " + entity.TableName + " SET ";
            //string values = "";
            //string condition = "";
            //int index = 0;

            //List<string> targetFields = GetTargetFields(entity.TableName, entity.PropertyNames, DB);
            ////构造查询语句
            //foreach (string field in targetFields)
            //{
            //    string paraName = "@P" + index.ToString();
            //    if (entity.PrimaryKeys.Contains(field))
            //    {
            //        //当前字段为主键,不能被更新
            //        condition += " AND " + field + "=" + paraName;
            //        //paras[index] = DB.GetParameter(paraName, entity.PropertyList(field));
            //    }
            //    else
            //    {
            //        values += "," + field + "=" + paraName;
            //        //paras[index] = DB.GetParameter(paraName, entity.PropertyList(field));

            //    }
            //    paras[index] = DB.GetParameter();
            //    paras[index].ParameterName = paraName;
            //    index++;
            //}


            //sql = sql + values.TrimStart(',') + " WHERE " + condition.Substring(" AND ".Length);

            EntityCommand ec = new EntityCommand(entity, DB);

            ec.TargetFields = GetTargetFields(entity.TableName, entity.PropertyNames, DB).ToArray();

            int all_count   = 0;
            int updateCount = 0;
            int insertCount = 0;
            List <IDataParameter> paraList = new List <IDataParameter>();

#if (!CMD_FAST)
            foreach (EntityBase item in entityList)
            {
                paraList.Clear();
                foreach (string field in ec.TargetFields)
                {
                    string         paraName = "@" + field.Replace(" ", "");
                    IDataParameter para     = DB.GetParameter(paraName, item.PropertyList(field));
                    paraList.Add(para);
                }


                //先做一部分修改,如果不成功就插入
                int count = DB.ExecuteNonQuery(ec.UpdateCommand, CommandType.Text, paraList.ToArray());
                if (count <= 0)
                {
                    insertCount += DB.ExecuteNonQuery(ec.InsertCommand, CommandType.Text, paraList.ToArray());
                }
                else
                {
                    updateCount += count;
                }
            }
#else
            IDbConnection conn = DB.GetDbConnection();

            IDbCommand insertCmd = conn.CreateCommand();
            insertCmd.CommandText = ec.InsertCommand;
            insertCmd.CommandType = CommandType.Text;
            if (ec.InsertParameters != null)
            {
                foreach (IDataParameter para in ec.InsertParameters)
                {
                    insertCmd.Parameters.Add(para);
                }
            }

            IDbCommand updateCmd = conn.CreateCommand();
            updateCmd.CommandText = ec.UpdateCommand;
            updateCmd.CommandType = CommandType.Text;
            if (ec.UpdateParameters != null)
            {
                foreach (IDataParameter para in ec.UpdateParameters)
                {
                    updateCmd.Parameters.Add(para);
                }
            }

            foreach (EntityBase item in entityList)
            {
                foreach (string field in ec.TargetFields)
                {
                    string paraName = DB.GetParameterChar + field.Replace(" ", "");
                    ((IDataParameter)insertCmd.Parameters[paraName]).Value = item.PropertyList(field);
                    ((IDataParameter)updateCmd.Parameters[paraName]).Value = item.PropertyList(field);
                }
                //先做一部分修改,如果不成功就插入
                //直接使用Command对象的 ExecuteNonQuery ,加快处理速度
                int count = updateCmd.ExecuteNonQuery();
                if (count <= 0)
                {
                    insertCount += insertCmd.ExecuteNonQuery();
                }
                else
                {
                    updateCount += count;
                }
            }
#endif
            all_count = insertCount + updateCount * (entityList.Count + 1);

            /* 更新或者修改计算方式
             * x + y * (C+1)=Z;{c=List Count;}
             * x + y = C;
             *   => y-y * (C+1)=C-Z => y(1-C-1)=C-Z => y * -C =C-Z => y= (C-Z) / -C
             * 在本例中,y=update,x=insert
             */
            return(all_count);
        }
Ejemplo n.º 4
0
        /// <summary>
        /// 初始化实体类信息,必须确保单线程调用本方法
        /// </summary>
        /// <param name="entityType"></param>
        /// <returns></returns>
        public bool InitEntity(Type entityType)
        {
            //未来版本,考虑不以EntityBase 明确类型来操作,避免在VS设计器无法类型转换到父类的问题
            object entity = Activator.CreateInstance(entityType);

            if (entityType.BaseType.FullName == "PWMIS.DataMap.Entity.EntityBase")
            {
                EntityBase instance = entity as EntityBase;
                if (instance != null)
                {
                    instance.PropertyChanging += instance_PropertyChanging;
                }

                this.tableName = (string)entityType.GetMethod("GetTableName").Invoke(entity, null);

                //var methodInfo = entityType.GetMethod("GetSetPropertyFieldName");
                //var testMethodInfo = entityType.GetMethod("TestWriteProperty", BindingFlags.Instance | BindingFlags.NonPublic);
                //testMethodInfo.Invoke(entity, null);//设置虚拟属性写入标记

                PropertyInfo[] propertys = entityType.GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly);
                //下面的方式弃用 dth 2015.2.8
                //int count = propertys.Length;
                //this.fields = new string[count];
                //this.propertyNames = new string[count];
                //this.typeNames = new Type[count];

                fieldList        = new List <string>();
                propertyNameList = new List <string>();
                typeNameList     = new List <Type>();

                //count = 0;
                string last_field = string.Empty;

                for (int i = 0; i < propertys.Length; i++)
                {
                    //获得调用的字段名称
                    //propertyNames[count] = propertys[i].Name;//获得调用的实体类属性名称
                    //typeNames[count] = propertys[i].PropertyType;
                    Type currPropType = propertys[i].PropertyType;

                    if (!propertys[i].CanWrite) //只读属性,跳过
                    {
                        continue;
                    }
                    try
                    {
                        currPropertyInfo = propertys[i];
                        //这里需要设置属性,以便获取字段长度
                        object Value = null;// 感谢网友 stdbool 发现byte[] 判断的问题
                        if (currPropType != typeof(string) && currPropType != typeof(byte[]))
                        {
                            Value = Activator.CreateInstance(currPropType);
                        }
                        currPropertyInfo.SetValue(entity, Value, null); //这里可能有普通属性在被赋值
                        //string field= (string)methodInfo.Invoke(entity,null);
                        //if (last_field != field)
                        //{
                        //    //跟之前的对比,确定当前是属性字段对应的属性
                        //    //fields[count] = field;
                        //    fieldList.Add(field);
                        //    propertyNameList.Add(currPropertyInfo.Name);
                        //    typeNameList.Add(currPropType);

                        //    last_field = field;
                        //}
                    }
                    catch
                    {
                        //return false;
                    }
                    //count++;
                }
                this.fields        = fieldList.ToArray();
                this.propertyNames = propertyNameList.ToArray();
                this.typeNames     = typeNameList.ToArray();
                this.entityType    = entityType;

                if (instance != null)
                {
                    instance.PropertyChanging -= instance_PropertyChanging;
                }
                return(true);
            }//end if
            return(false);
        }
Ejemplo n.º 5
0
        /// <summary>
        /// 为实体类的一个属性创建对应的数据库表的列的脚本
        /// </summary>
        /// <param name="db"></param>
        /// <param name="entity"></param>
        /// <param name="field"></param>
        /// <returns></returns>
        public string CreateTableColumnScript(AdoHelper db, EntityBase entity, string field)
        {
            Type   t            = this.GetPropertyType(field);
            object defaultValue = null;

            if (t == typeof(string))
            {
                defaultValue = "";
            }
            else if (t == typeof(byte[]))
            {
                defaultValue = new byte[1];//这里只是构造默认值,不需要实际的长度
            }
            else
            {
                defaultValue = Activator.CreateInstance(t);
            }

            IDataParameter para = db.GetParameter(field, defaultValue);
            //需要再获取参数长度

            string temp = "";

            if (t == typeof(string))
            {
                int length = entity.GetStringFieldSize(field);
                if (length == 0) //实体类未定义属性字段的长度
                {
                    string fieldType = "text";
                    if (db is SqlServer) //此处要求SqlServer 2005以上,SqlServer2000 不支持
                    {
                        fieldType = "varchar(max)";
                    }
                    if (db.CurrentDBMSType == DBMSType.SqlServerCe)
                    {
                        fieldType = "ntext";
                    }
                    temp = temp + "[" + field + "] " + fieldType;
                }
                else if (length > 0)
                {
                    //并不是所有数据库都支持nvarchar,有关数据库字符串类型的详细支持,请看 http://www.cnblogs.com/hantianwei/p/3152517.html
                    string fieldType = "varchar";
                    if (db.CurrentDBMSType == DBMSType.SqlServer ||
                        db.CurrentDBMSType == DBMSType.Oracle ||
                        db.CurrentDBMSType == DBMSType.SqlServerCe)
                    {
                        fieldType = "nvarchar";
                    }
                    temp = temp + "[" + field + "] " + fieldType + "(" + length + ")";
                }
                else if (length < 0)
                {
                    temp = temp + "[" + field + "] varchar" + "(" + length + ")";
                }
            }
            else if (t == typeof(byte[])) //感谢CSDN网友 ccliushou 发现此问题,原贴:http://bbs.csdn.net/topics/391967495
            {
                int length = entity.GetStringFieldSize(field);
                temp = temp + "[" + field + "] " + db.GetNativeDbTypeName(para);
                if (length == 0)
                {
                    temp = temp + "(max)";
                }
                else
                {
                    temp = temp + "(" + length + ")";
                }
            }
            else
            {
                temp = temp + "[" + field + "] " + db.GetNativeDbTypeName(para);
            }

            if (field == entity.IdentityName)
            {
                if (db.CurrentDBMSType == PWMIS.Common.DBMSType.SqlServer || db.CurrentDBMSType == PWMIS.Common.DBMSType.SqlServerCe)
                {
                    temp = temp + " IDENTITY(1,1)";
                }
                else if (db.CurrentDBMSType == PWMIS.Common.DBMSType.Access)
                {
                    temp = temp.Replace("Integer", " autoincrement");
                }
                else if (db.CurrentDBMSType == PWMIS.Common.DBMSType.SQLite)
                {
                    temp = temp + " autoincrement";
                }
                else if (db.CurrentDBMSType == PWMIS.Common.DBMSType.MySql)
                {
                    temp = temp + " AUTO_INCREMENT";
                }
                else if (db.CurrentDBMSType == PWMIS.Common.DBMSType.PostgreSQL)
                {
                    temp = temp + " DEFAULT nextval('" + entity.TableName + "_" + entity.IdentityName + "_" + "seq'::regclass) NOT NULL";
                }
                else
                {
                    //Oracle 采用序列和触发器,这里不处理
                }
            }
            //identity(1,1) primary key
            //Access 要求主键申明必须在自增之后,否则语法错误
            if (entity.PrimaryKeys.Contains(field))
            {
                temp = temp + " PRIMARY KEY";
            }
            return(db.GetPreparedSQL(temp));
        }
Ejemplo n.º 6
0
        /// <summary>
        /// 二进制序列化
        /// </summary>
        /// <param name="entity">实体类实例</param>
        /// <returns>字节数组</returns>
        public static byte[] BinarySerialize(EntityBase entity)
        {
            MemoryStream ms             = new MemoryStream();
            BinaryWriter bw             = new BinaryWriter(ms);
            Type         factEntityType = entity.GetType();
            EntityFields ef             = EntityFieldsCache.Item(factEntityType);
            byte         b;

            //写入实体类标记
            bw.Write(ENTITY_ITEM_FLAG);
            int length = entity.PropertyValues.Length - 1;

            for (int i = 0; i <= length; i++)
            {
                object obj = entity.PropertyValues[i];
                //if (obj == System.DBNull.Value) obj = null;//DBNull.Value在Convert 的时候会失败
                //为每个属性添加null标记
                if (obj == System.DBNull.Value || obj == null)
                {
                    b = 0;//NULL标记
                }
                else
                {
                    if (length == i)
                    {
                        b = byte.MaxValue;
                    }
                    else
                    {
                        b = 1;                                     //如果标志位为 byte.MaxValue ,则表示已经写入所有的属性字段,可用于以后添加实体属性但又要成功读取原有的记录
                    }
                }


                bw.Write(b); //写入标记
                if (b > 0)
                {
                    Type propertyType = ef.GetPropertyType(entity.PropertyNames[i]);
                    if (propertyType == null)
                    {
                        throw new Exception("PDF.NET实体类序列化错误:未知的实体属性类型,请检查实体类的属性和字段定义是否匹配。");
                    }

                    switch (propertyType.Name)
                    {
                    case "Int32":
                        bw.Write(Convert.ToInt32(obj)); break;

                    case "String":
                        bw.Write(Convert.ToString(obj));
                        break;

                    case "DateTime":
                        bw.Write(Convert.ToDateTime(obj).ToBinary());
                        break;

                    case "Int16": bw.Write(Convert.ToInt16(obj)); break;

                    case "Int64": bw.Write(Convert.ToInt64(obj)); break;

                    case "Single": bw.Write(Convert.ToSingle(obj)); break;

                    case "Double": bw.Write(Convert.ToDouble(obj)); break;

                    case "Decimal": bw.Write(Convert.ToDecimal(obj)); break;

                    case "Boolean": bw.Write(Convert.ToBoolean(obj)); break;

                    case "Byte": bw.Write(Convert.ToByte(obj)); break;

                    case "Char": bw.Write(Convert.ToChar(obj)); break;

                    case "Byte[]":
                        Byte[] buffer = (Byte[])obj;
                        bw.Write(buffer.Length);    //写入字节序列的长度
                        if (buffer.Length > 0)
                        {
                            bw.Write(buffer);
                        }
                        break;
                    }
                }
            }

            bw.Close();
            ms.Close();
            return(ms.ToArray());
        }
Ejemplo n.º 7
0
        /// <summary>
        /// 初始化实体信息(已经过时)
        /// </summary>
        /// <param name="entityType"></param>
        /// <returns></returns>
        public bool Init(Type entityType)
        {
            //未来版本,考虑不以EntityBase 明确类型来操作,避免在VS设计器无法类型转换到父类的问题
            EntityBase entity = Activator.CreateInstance(entityType) as EntityBase;

            if (entity != null)
            {
                entity.PropertyGetting += new EventHandler <PropertyGettingEventArgs>(entity_PropertyGetting);
                int count = entity.PropertyNames.Length;
                this.fields        = new string[count];
                this.propertyNames = new string[count];
                this.typeNames     = new Type[count];
                this.tableName     = entity.TableName;

                PropertyInfo[] propertys = entityType.GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly);
                count = 0;

                for (int i = 0; i < propertys.Length; i++)
                {
                    this.currPropName = null;
                    try
                    {
                        propertys[i].GetValue(entity, null);//获取属性,引发事件
                    }
                    catch
                    {
                        this.currPropName = null;
                    }

                    if (this.currPropName != null)
                    {
                        //如果在分布类中引用了原来的属性,currPropName 可能会有重复
                        bool flag = false;
                        foreach (string str in fields)
                        {
                            if (str == this.currPropName)
                            {
                                flag = true;
                                break;
                            }
                        }
                        if (!flag)
                        {
                            fields[count]        = this.currPropName; //获得调用的字段名称
                            propertyNames[count] = propertys[i].Name; //获得调用的实体类属性名称
                            typeNames[count]     = propertys[i].PropertyType;
                            try
                            {
                                //这里需要设置属性,以便获取字段长度
                                object Value = null;// 感谢网友 stdbool 发现byte[] 判断的问题
                                if (typeNames[count] != typeof(string) && typeNames[count] != typeof(byte[]))
                                {
                                    Value = Activator.CreateInstance(typeNames[count]);
                                }
                                propertys[i].SetValue(entity, Value, null);
                            }
                            catch
                            {
                            }
                            count++;
                        }
                    }
                }
                return(true);
            }
            return(false);
        }
Ejemplo n.º 8
0
        protected internal static void  BinaryDeserializeCommon(BinaryReader br, EntityFields ef, EntityBase factEntity)
        {
            int flag = br.ReadInt32();

            if (flag != PdfNetSerialize.ENTITY_ITEM_FLAG)
            {
                throw new Exception("反序列化错误:不是有效的实体类数据格式!");
            }

            byte FieldFlag;

            for (int i = 0; i < factEntity.PropertyValues.Length; i++)
            {
                object obj = null;
                FieldFlag = br.ReadByte();
                if (FieldFlag == 0)
                {
                    obj = DBNull.Value;
                }
                else
                {
                    Type propertyType = ef.GetPropertyType(factEntity.PropertyNames[i]);
                    if (propertyType == null)
                    {
                        throw new Exception("PDF.NET实体类序列化错误:未知的实体属性类型,请检查实体类的属性和字段定义是否匹配。");
                    }

                    switch (propertyType.Name)
                    {
                    case "Int32": obj = br.ReadInt32(); break;

                    case "String":
                        obj = br.ReadString();    //继续读一个字符串
                        break;

                    case "DateTime": obj = DateTime.FromBinary(br.ReadInt64()); break;

                    case "Int16": obj = br.ReadInt16(); break;

                    case "Int64": obj = br.ReadInt64(); break;

                    case "Single": obj = br.ReadSingle(); break;

                    case "Double": obj = br.ReadDouble(); break;

                    case "Decimal": obj = br.ReadDecimal(); break;

                    case "Boolean": obj = br.ReadBoolean(); break;

                    case "Byte": obj = br.ReadByte(); break;

                    case "Char": obj = br.ReadChar(); break;

                    case "Byte[]":
                        int length = br.ReadInt32();
                        if (length > 0)
                        {
                            obj = br.ReadBytes(length);
                        }
                        break;
                    }
                }

                factEntity.PropertyValues[i] = obj;
                if (FieldFlag == byte.MaxValue)
                {
                    break;//属性已经读取完成,不再处理当前实体的其它字段
                }
            }
        }
Ejemplo n.º 9
0
        /// <summary>
        /// 将数据从查询结果容器中映射到实体中
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public IEnumerable <T> Map <T>() where T : EntityBase, new()
        {
            #region 旧方法代码,注释

            /*
             * if (this.Values == null)
             * {
             *  int rowsCount = this.Execute();
             *  if (rowsCount <= 0)
             *      yield break;
             *
             * }
             * if (this.Values != null && this.fieldNames != null)
             * {
             *  if (this.Values.Count == 0)
             *      yield break;
             *
             *  Dictionary<string, int> dictNameIndex = new Dictionary<string, int>();
             *  T entity = new T();
             *  string tabeName = entity.TableName;
             *  //查找字段匹配情况
             *  //entity.PropertyNames 存储的仅仅是查询出来的列名称,由于有连表查询,
             *  //如果要映射到指定的实体,还得检查当前列对应的表名称
             *  if (this.OQL.sql_fields.Contains("[" + tabeName + "]"))
             *  {
             *      //是连表查询
             *      for (int i = 0; i < this.fieldNames.Length; i++)
             *      {
             *          for (int j = 0; j < entity.PropertyNames.Length; j++)
             *          {
             *              string cmpString = "[" + tabeName + "].[" + entity.PropertyNames[j] + "]";
             *              if (this.OQL.sql_fields.Contains(cmpString))
             *              {
             *                  dictNameIndex[this.fieldNames[i]] = i;
             *                  break;
             *              }
             *          }
             *
             *
             *      }
             *  }
             *  else
             *  {
             *      for (int i = 0; i < this.fieldNames.Length; i++)
             *      {
             *          for (int j = 0; j < entity.PropertyNames.Length; j++)
             *          {
             *              if (this.fieldNames[i] == entity.PropertyNames[j])
             *              {
             *                  dictNameIndex[this.fieldNames[i]] = i;
             *                  break;
             *              }
             *          }
             *      }
             *  }
             *
             *  //没有匹配的,提前结束
             *  if (dictNameIndex.Count == 0)
             *      yield break;
             *
             *  int length = entity.PropertyValues.Length;
             *  foreach (object[] itemValues in this.Values)
             *  {
             *      for (int m = 0; m < length; m++)
             *      {
             *          //将容器的值赋值给实体的值元素
             *          string key = entity.PropertyNames[m];
             *          if (dictNameIndex.ContainsKey(key))
             *              entity.PropertyValues[m] = itemValues[dictNameIndex[key]];
             *      }
             *      yield return entity;
             *      //创建一个新实例
             *      entity = new T ();
             *  }
             * }
             * else
             * {
             *  throw new Exception("EntityContainer 错误,执行查询没有返回任何行。");
             * }
             */
            #endregion

            if (this.Values == null)
            {
                //可能执行本方法之前,并没有调用过 OQL的Select方法指定要查询的实体类属性,需要模拟调用一次。
                if (this.OQL.selectedFieldInfo.Count == 0)
                {
                    int fieldCount = 0;
                    foreach (EntityBase entity in this.OQL.GetAllUsedEntity())
                    {
                        for (int i = 0; i < entity.PropertyNames.Length; i++)
                        {
                            object value = entity[i];//模拟调用
                            fieldCount++;
                        }
                    }
                    this.OQL.Select(new object[fieldCount]);
                }
                int rowsCount = this.Execute();
                if (rowsCount <= 0)
                {
                    yield break;
                }
            }
            if (this.Values != null && this.fieldNames != null)
            {
                if (this.Values.Count == 0)
                {
                    yield break;
                }

                TableNameField[] fieldInfo = new TableNameField[this.OQL.selectedFieldInfo.Count];
                //查找字段匹配情况
                //entity.PropertyNames 存储的仅仅是查询出来的列名称
                for (int i = 0; i < this.OQL.selectedFieldInfo.Count; i++)
                {
                    TableNameField tnf = this.OQL.selectedFieldInfo[i];
                    tnf.Index    = tnf.Entity.GetPropertyFieldNameIndex(tnf.Field);
                    fieldInfo[i] = tnf;
                }

                foreach (object[] itemValues in this.Values)
                {
                    EntityBase itemEntity = null;
                    Type       entityType = typeof(T);

                    for (int m = 0; m < fieldInfo.Length; m++)
                    {
                        //将容器的值赋值给实体的值元素
                        EntityBase entity = fieldInfo[m].Entity;
                        if (entity.GetType() == entityType)
                        {
                            itemEntity = entity;
                            int index = fieldInfo[m].Index;
                            entity.PropertyValues[index] = itemValues[m];
                        }
                    }
                    if (itemEntity == null)
                    {
                        throw new Exception("EntityContainer 错误,查询没有包含当前指定的实体类类型,请检查OQL语句。");
                    }
                    T resultEntity = (T)itemEntity.Clone();
                    yield return(resultEntity);
                }
            }
            else
            {
                throw new Exception("EntityContainer 错误,执行查询没有返回任何行。");
            }
        }
Ejemplo n.º 10
0
 public EntityCommand(EntityBase entity, CommonDB db)
 {
     this.currEntity = entity;
     this.currDb     = db;
 }
Ejemplo n.º 11
0
 public OQLCompare(EntityBase e, params EntityBase[] joinedEntitys)
 {
 }
Ejemplo n.º 12
0
 public OQLCompare(EntityBase e)
 {
 }