コード例 #1
0
        private static bool AddParameter <T>(SqlCommand cmd, string field, object item, TableMap <T> map)
            where T : class, new()
        {
            var type = item.GetType();

            if (!map.KeyFields.Contains(field) || map.HasAutoId)
            {
                if (map.ReadonlyFields != null && map.ReadonlyFields.Contains(field))
                {
                    return(false);
                }
            }

            var prop = type.GetProperty(field);

            if (map.IsReference(field))
            {
                try
                {
                    var refValue = map.GetReferenceValue(item, field);
                    cmd.Parameters.AddWithValue(field, refValue ?? DBNull.Value);
                    return(true);
                }
                catch
                {
                    // member not present
                    Debug.Print("Field {0} not present on object {1}", field, item);
                }
            }
            else if (prop != null)
            {
                var param = cmd.Parameters.AddWithValue(field, prop.GetValue(item, null) ?? DBNull.Value);
                if (param.Value == DBNull.Value || param.Value is string strVal && string.IsNullOrEmpty(strVal))
                {
                    if (prop.PropertyType == typeof(byte[]))
                    {
                        param.SqlDbType = SqlDbType.Binary;
                    }
                }

                return(true);
            }
            else if (field.EndsWith("Id"))
            {
                var refField = field.Substring(0, field.Length - 2);
                prop = type.GetProperty(refField);
                if (prop != null)
                {
                    var refItem = prop.GetValue(item, null);
                    if (refItem != null)
                    {
                        var refType = prop.PropertyType;
                        var refProp = refType.GetProperty("Id");
                        cmd.Parameters.AddWithValue(field, refProp.GetValue(refItem, null) ?? DBNull.Value);
                    }
                    else
                    {
                        cmd.Parameters.AddWithValue(field, DBNull.Value);
                    }
                    return(true);
                }
            }
            return(false);
        }