Esempio n. 1
0
        internal CPQuery GetUpdateQuery(Tuple <string, object> rowKey)
        {
            IEntityProxy proxy = this as IEntityProxy;

            string[] names  = proxy.GetChangeNames();
            object[] values = proxy.GetChangeValues();
            if (names.Length == 0)
            {
                return(null);                       // 没有设置任何属性,应该不会发生吧?
            }
            int keyIndex = -1;                      // 标记主键字段在数组的哪个位置

            if (rowKey != null)
            {
                keyIndex = Array.IndexOf(names, rowKey.Item1);
            }

            if (names.Length == 1 && keyIndex == 0)
            {
                return(null);                       // 如果仅仅只设置了主键字段,这样的更新是无意义的
            }
            int forcount = values.Length;

            if (keyIndex == forcount - 1)                       // 主键出现在最后面
            {
                forcount--;
            }

            CPQuery query = this.DbContext.CreateCPQuery()
                            + "UPDATE " + GetTableName() + " SET ";

            for (int i = 0; i < forcount; i++)
            {
                if (i == keyIndex)                              // 忽略主键字段
                {
                    continue;
                }

                string name  = names[i];
                object value = values[i];

                if (value == null)
                {
                    query = query + " " + name + "=NULL";
                }
                else
                {
                    query = query + " " + name + "=" + new QueryParameter(value);
                }

                if (i < forcount - 1)
                {
                    query.AppendSql(",");                               // 注意,这个逗号的拼接,有可能主键出现在所有字段的最后。
                }
            }

            return(query);
        }
Esempio n. 2
0
        internal CPQuery GetInsertQuery()
        {
            IEntityProxy proxy = this as IEntityProxy;

            string[] names  = proxy.GetChangeNames();
            object[] values = proxy.GetChangeValues();
            if (names.Length == 0)
            {
                return(null);                       // 没有设置任何属性,应该不会发生吧?
            }
            CPQuery query = this.DbContext.CreateCPQuery();

            query = query
                    + "INSERT INTO " + GetTableName() + "("
                    + string.Join(",", names.ToArray())
                    + ") VALUES (";


            for (int i = 0; i < values.Length; i++)
            {
                object value = values[i];
                if (value == null)
                {
                    query = query + "NULL";
                }
                else
                {
                    query = query + new QueryParameter(value);
                }

                if (i < values.Length - 1)
                {
                    query.AppendSql(",");
                }
            }

            query.AppendSql(")");

            return(query);
        }