コード例 #1
0
        public System.Data.IDbCommand GenerateSelectItemsSql <T>(object ob, PropertyInfo ParentInfo)
        {
            //初始化一个Command
            System.Data.SqlClient.SqlCommand command = null;
            var       TargetType = typeof(T);
            var       ParentType = ob.GetType();
            ORMHelper helper     = new ORMHelper();

            command = new System.Data.SqlClient.SqlCommand();
            String TableName = helper.GetTable(TargetType);

            var Properties = TargetType.GetProperties();


            String Cols = "";


            String       WhereSql   = "";
            PropertyInfo ParentKey  = null;
            String       ColumnName = "";


            var parentAttribute = ParentInfo.GetCustomAttributes(typeof(ParentRelationAttribute), true);

            if (parentAttribute.Length > 0)
            {
                ColumnName = (parentAttribute[0] as ParentRelationAttribute).ColumnName;
                //  ParentKey = ParentType.GetProperty(parentInfo.PropertyName);
            }
            else
            {
                var columAttribute = ParentInfo.GetCustomAttributes(typeof(ColumnAttribute), true);

                if (columAttribute.Length > 0)
                {
                    ColumnName = (columAttribute[0] as ColumnAttribute).ColumnName;
                }
            }


            ParentKey = new ORMHelper().GetKeyPropertyInfo(ParentInfo.PropertyType);
            if (ParentKey != null)
            {
                command.Parameters.Add(new SqlParameter("@" + ColumnName,
                                                        ParentKey.GetValue(ob, null) ?? ""));
                WhereSql = "where  [" + ColumnName + "]=@" + ColumnName
                ;
            }

            for (int i = 0; i < Properties.Length; i++)
            {
                if (Properties[i] != ParentInfo)
                {
                    foreach (var Col in helper.GetColNameAttributes(Properties[i]))
                    {
                        String paramName = "@" + helper.GetColName(Col, Properties[i]);
                        string ColName   = helper.GetColName(Col, Properties[i]);

                        if (Col.NoMap)
                        {
                            continue;
                        }
                        ColName = Col.ColumnName;

                        if (String.IsNullOrEmpty(ColName))
                        {
                            ColName = Properties[i].Name;
                        }
                        Cols += TableName + ".[" + ColName + "],";
                        //   }
                    }
                }
            }

            command.CommandText = "SELECT " + Cols.Substring(0, Cols.Length - 1) + " FROM " + TableName + WhereSql;   //+ "(" +

            return(command);
        }