예제 #1
0
        /// <summary>
        /// Creates a new instance of DbParameter[] with ParameterName, Value and IsNullable properties
        /// sets to value's properties.
        /// </summary>
        /// <typeparam name="T">Type of object with properties to convert in Parameters</typeparam>
        /// <typeparam name="U">DbParameter type (SqlParameter, ...)</typeparam>
        /// <param name="command"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        private static IEnumerable <DbParameter> ToParameters <T, U>(DbCommand command, T value) where U : DbParameter
        {
            if (TypeExtension.IsPrimitive(typeof(T)))
            {
                throw new ArgumentException("The value can not be a simple type (string, int, ...), but an object with simple properties.", "value");
            }
            else
            {
                List <DbParameter> parameters = new List <DbParameter>();
                foreach (PropertyInfo property in typeof(T).GetProperties())
                {
                    if (TypeExtension.IsPrimitive(property.PropertyType))
                    {
                        // Data type
                        Type propType = TypeExtension.GetNullableSubType(property.PropertyType);

                        // Value
                        DbParameter parameter = command != null?
                                                command.CreateParameter() :
                                                    Activator.CreateInstance(typeof(U)) as DbParameter;

                        parameter.Value      = typeof(T).GetProperty(property.Name).GetValue(value, null);
                        parameter.IsNullable = TypeExtension.IsNullable(property.PropertyType);
                        parameter.DbType     = DbTypeMap.FirstDbType(propType);

                        if (parameter.IsNullable && parameter.Value == null)
                        {
                            parameter.Value = DBNull.Value;
                        }

                        // Parameter name
                        string attribute = Apps72.Dev.Data.Annotations.ColumnAttribute.GetColumnAttributeName(property);
                        if (string.IsNullOrEmpty(attribute))
                        {
                            parameter.ParameterName = property.Name;
                        }
                        else
                        {
                            parameter.ParameterName = attribute;
                        }

                        parameters.Add(parameter);
                    }
                }

                return(parameters.AsEnumerable());
            }
        }