/// <summary> /// 创建新的XmlCommand对象。 /// </summary> /// <param name="name">命令名字</param> /// <param name="argsObject">匿名对象表示的参数</param> /// <param name="replaces">替换的关键字字典</param> public XmlCommand(string name, object argsObject, Dictionary <string, string> replaces) { if (string.IsNullOrEmpty(name)) { throw new ArgumentNullException("name"); } XmlCommandItem command = XmlCommandManager.GetCommand(name); if (command == null) { throw new ArgumentOutOfRangeException("name", string.Format("指定的XmlCommand名称 {0} 不存在。", name)); } // 根据XML的定义以及传入参数,生成IDictionary IDictionary <string, object> parameters = GetParameters(command, argsObject); // 创建CPQuery实例 StringBuilder commandText = new StringBuilder(command.CommandText); if (replaces != null) { foreach (KeyValuePair <string, string> kvp in replaces) { commandText.Replace(kvp.Key, kvp.Value); } } _query.SetParam(parameters); _query.SqlBuilder.Append(commandText.ToString()); }
/// <summary> /// 根据XmlCommandItem对象,返回OracleParameter对象数组 /// </summary> /// <param name="command">XmlCommandItem对象实例</param> /// <param name="argsObject">匿名对表示的数据库参数</param> /// <returns>OracleParameter对象数组</returns> private IDictionary <string, object> GetParameters(XmlCommandItem command, object argsObject) { IDictionary <string, object> result = new Dictionary <string, object>(); if (command == null) { throw new ArgumentNullException("command"); } if (argsObject == null || command.Parameters.Count == 0) { return(result); } PropertyInfo[] properties = argsObject.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public); // 赋值。 foreach (PropertyInfo pInfo in properties) { string name = ":" + pInfo.Name; XmlCmdParameter p = command.Parameters.FirstOrDefault(x => string.Compare(x.Name, name, StringComparison.OrdinalIgnoreCase) == 0); // 如果传入了在XML中没有定义的参数项,则会抛出异常。 if (p == null) { throw new ArgumentException(string.Format("传入的参数对象中,属性 {0} 没有在XML定义对应的参数名。", pInfo.Name)); } result.Add(p.Name, pInfo.FastGetValue(argsObject) ?? DBNull.Value); } return(result); }