Ejemplo n.º 1
0
        internal static object[] GetModifyKeyValues <TEntity>(object entity)
        {
            if (entity == null)
            {
                throw new ArgumentNullException(nameof(entity));
            }

            var mapper1 = TypeMapper.Instance <TEntity> .Mapper.ThrowWithNotFoundKeys();

            var mapper2   = TypeMapper.Create(entity.GetType());
            var keyValues = new List <object>(mapper1.KeyProperties.Length * 2);

            foreach (var keyProp1 in mapper1.KeyProperties)
            {
                keyValues.Add(keyProp1.Name);
                var keyValue = mapper2[keyProp1.Name]?.GetValue(entity, true);
                if (keyValue == null)
                {
                    throw CreateKeyNotFoundException <TEntity>(keyProp1.Name);
                }

                keyValues.Add(keyValue);
            }
            return(keyValues.ToArray());
        }
Ejemplo n.º 2
0
        /// <summary>
        /// 同时设置哈希表 <paramref name="key"/> 中一个或多个域值。
        /// </summary>
        /// <param name="client">Redis 客户端。</param>
        /// <param name="key">键名</param>
        /// <param name="fieldValues">域值的匿名对象。</param>
        /// <returns>结果。</returns>
        public static Result HMSet(this IRedisClient client, string key, object fieldValues)
        {
            if (client == null)
            {
                throw new ArgumentNullException(nameof(client));
            }
            if (fieldValues == null)
            {
                throw new ArgumentNullException(nameof(fieldValues));
            }
            RedisDictionary redisDict;

            if (fieldValues is System.Collections.IDictionary)
            {
                redisDict = new RedisDictionary(fieldValues as System.Collections.IDictionary);
            }
            else
            {
                var typeMapper = TypeMapper.Create(fieldValues.GetType());
                redisDict = new RedisDictionary(typeMapper.Count);
                foreach (var propertyMapper in typeMapper.Properties)
                {
                    redisDict.Add(propertyMapper.Name, BinaryValue.Create(propertyMapper.GetValue(fieldValues, false), propertyMapper.Property));
                }
            }
            return(HMSet(client, key, redisDict));
        }
Ejemplo n.º 3
0
        /// <summary>
        /// 将当前对象所有的属性值复制到 <paramref name="target"/>。
        /// </summary>
        /// <typeparam name="TTarget">目标的数据类型。</typeparam>
        /// <param name="source">复制的源对象。</param>
        /// <param name="target">复制的目标对象。</param>
        /// <param name="targetStrategy">复制目标的策略。</param>
        /// <returns> <paramref name="target"/>。</returns>
        public static TTarget CopyTo <TTarget>(this object source, TTarget target, CopyToStrategy targetStrategy = CopyToStrategy.Default)
        {
            if (source == null)
            {
                throw new ArgumentNullException(nameof(source));
            }
            if (target == null)
            {
                throw new ArgumentNullException(nameof(target));
            }

            var sMapper = TypeMapper.Create(source.GetType());
            var tMapper = TypeMapper.Create(target.GetType());

            foreach (var sProperty in sMapper.Properties)
            {
                var tProperty = tMapper[sProperty.Name];
                if (tProperty == null)
                {
                    continue;
                }
                if (targetStrategy == CopyToStrategy.OnlyPrimaryKey && !tProperty.IsKey ||
                    (targetStrategy == CopyToStrategy.ExcludePrimaryKey && tProperty.IsKey) ||
                    !tProperty.Property.CanWrite)
                {
                    continue;
                }

                object sValue = sProperty.GetValue(source, false);

                if (targetStrategy == CopyToStrategy.OnlyChangeValues)
                {
                    if (object.Equals(sValue, sProperty.TypeDefaultValue))
                    {
                        continue;
                    }
                }

                var spType = sProperty.Property.PropertyType;
                var tpType = tProperty.Property.PropertyType;

                if (spType != tpType)
                {
                    if (tpType.IsValueType && sValue == null)
                    {
                        //throw new ArgumentNullException("{0}.{1}".Fmt(sMapper.Type.Name, sProperty.Property.Name), "目标属性 {0}.{1} 不能为 null 值。".Fmt(tMapper.Type.Name, tProperty.Property.Name));
                        continue;
                    }
                    tProperty.SetValue(target, tpType.ChangeType(sValue), false);
                }
                else
                {
                    tProperty.SetValue(target, sValue, false);
                }
            }
            return(target);
        }
Ejemplo n.º 4
0
        /// <summary>
        /// 提供匹配条件,执行一个更新的命令,可以是匿名对象的部分成员(<paramref name="entity"/> 属性成员和 <typeparamref name="TEntity"/> 属性成员必须一致)。
        /// </summary>
        /// <typeparam name="TEntity">实体的数据类型。</typeparam>
        /// <param name="engine">数据源查询与交互引擎的实例。</param>
        /// <param name="entity">实体的实例对象,可以是匿名对象的部分成员(<paramref name="entity"/> 属性成员和 <typeparamref name="TEntity"/> 属性成员必须一致)。</param>
        /// <param name="where">条件表达式。</param>
        /// <param name="ps">参数集合实例。</param>
        public static DbResult <int> ModifyWhere <TEntity>(this IDbEngine engine, object entity, string where, ExecuteParameterCollection ps = null)
        {
            if (engine == null)
            {
                throw new ArgumentNullException("engine");
            }
            if (entity == null)
            {
                throw new ArgumentNullException("entity");
            }

            var mapper1     = TypeMapper.Instance <TEntity> .Mapper;
            var mapper2     = TypeMapper.Create(entity.GetType());
            var parSettings = engine.Owner.Injector.ParameterSettings;
            var setBuilder  = new StringBuilder("UPDATE ")
                              .Append(parSettings.EscapeName(mapper1.Name))
                              .Append(" SET ");
            int index = 0;

            if (ps == null)
            {
                ps = new ExecuteParameterCollection();
            }
            foreach (var property2 in mapper2.Properties)
            {
                if (property2.IsIgnore || property2.IsKey)
                {
                    continue;
                }
                if (!mapper1.Contains(property2.Name))
                {
                    throw new NotSupportedException("表 {0} 没有属性 {1}。".Fmt(mapper1.Name, property2.Name));
                }
                if (index > 0)
                {
                    setBuilder.Append(',');
                }

                setBuilder.Append(parSettings.EscapeName(property2.Name))
                .Append('=')
                .Append(parSettings.PrefixWithText)
                .Append("_value_")
                .Append(index);
                ps.Add(parSettings.PrefixWithCollection + "_value_" + index, property2.GetValue(entity));
                index++;
            }
            if (where != null)
            {
                setBuilder.Append(" WHERE ").Append(where);
            }
            return(engine.Execute(setBuilder.ToString(), ps).ToNonQuery());
        }
Ejemplo n.º 5
0
        private static CompareResult Compare(string name, Type type, object t1, object t2)
        {
            type = type.GetNullableType();
            switch (Type.GetTypeCode(type))
            {
            case TypeCode.Object:
                if (t1 == null || t2 == null)
                {
                    goto default;
                }
                if (type.IsSubclassOf(Types.Exception) || type == Types.Exception)
                {
                    t1 = t1.ToString();
                    t2 = t2.ToString();
                    goto default;
                }
                var mp = TypeMapper.Create(type);
                foreach (var p in mp.Properties)
                {
                    try
                    {
                        var v1 = p.GetValue(t1);
                        var v2 = p.GetValue(t2);
                        var r  = Compare(p.Property.Name, p.Property.PropertyType, v1, v2);
                        if (r != null)
                        {
                            return(null);
                        }
                    }
                    catch (Exception)
                    {
                        throw;
                    }
                }
                break;

            default:
                if (!object.Equals(t1, t2))
                {
                    return(new CompareResult()
                    {
                        Name = name,
                        Value1 = t1,
                        Value2 = t2
                    });
                }
                break;
            }
            return(null);
        }
Ejemplo n.º 6
0
        internal static object[] GetKeyValues <TEntity>(string keyName, object keyValue)
        {
            if (keyValue == null)
            {
                throw new ArgumentNullException(nameof(keyValue));
            }

            var keyValues = new List <object>(2);

            if (string.IsNullOrWhiteSpace(keyName))
            {
                var mapper = TypeMapper.Instance <TEntity> .Mapper.ThrowWithNotFoundKeys();

                if (mapper.KeyProperties.Length == 1)
                {
                    keyName = mapper.KeyProperties[0].Name;
                }
                else
                {
                    var keyValueType = keyValue.GetType();
                    if (keyValueType.IsSimpleType())
                    {
                        throw new NotSupportedException($"类型“{typeof(TEntity).FullName}”包含多个主键,{nameof(keyValue)} 参数所有值都必须是一个复杂对象。");
                    }

                    var mapper2 = TypeMapper.Create(keyValueType);
                    foreach (var keyProp in mapper.KeyProperties)
                    {
                        keyValues.Add(keyProp.Name);
                        var tmpKV = mapper2[keyProp.Name]?.GetValue(keyValue, true);
                        if (tmpKV == null)
                        {
                            throw CreateKeyNotFoundException <TEntity>(keyProp.Name);
                        }
                        keyValues.Add(tmpKV);
                    }
                }
            }

            if (keyValues.Count == 0)
            {
                keyValues.Add(keyName);
                keyValues.Add(keyValue);
            }
            return(keyValues.ToArray());
        }
Ejemplo n.º 7
0
        internal static WhereParameters GetRemoveWhere <TEntity>(this IDbEngine engine, object entityOrPKValues)
        {
            if (engine == null)
            {
                throw new ArgumentNullException(nameof(engine));
            }
            if (entityOrPKValues == null)
            {
                throw new ArgumentNullException(nameof(entityOrPKValues));
            }

            /*
             * 1、Remove(val)
             * 2、Remove({key=val})
             * 3、Remove({key=val1},val2)
             * 4、Remove([{key1=val2,key2=val2},{key1=val3,key2=val4}])
             */

            var mapper = TypeMapper.Instance <TEntity> .Mapper.ThrowWithNotFoundKeys();

            if (!(entityOrPKValues is string) && entityOrPKValues is Collections.IEnumerable)
            {
                entityOrPKValues = ((Collections.IEnumerable)entityOrPKValues).Cast <object>().ToArray();
            }

            var type = entityOrPKValues.GetType();

            if (mapper.KeyProperties.Length == 1)
            {//- 单个主键,1,2,3
                var keyName = mapper.KeyProperties[0].Name;

                if (type.IsArray)
                {//-3
                    var           array     = (Array)entityOrPKValues;
                    List <object> newValues = new List <object>(array.Length);
                    foreach (var item in array)
                    {
                        var itemType = item.GetType();
                        if (itemType.IsSimpleType())
                        {
                            newValues.Add(item);
                        }
                        else
                        {
                            var keyValue = TypeMapper.Create(itemType)[keyName]?.GetValue(item, true);
                            if (keyValue == null)
                            {
                                throw CreateKeyNotFoundException <TEntity>(keyName);
                            }
                            newValues.Add(keyValue);
                        }
                    }
                    var builder = new SqlBuilder(engine);
                    builder.Where(keyName, keyName, newValues.ToArray());
                    return(new WhereParameters(builder.WhereText, builder.Parameters));
                }
                if (!type.IsSimpleType())
                {//-2
                    entityOrPKValues = TypeMapper.Create(type)[keyName]?.GetValue(entityOrPKValues, true);
                    if (entityOrPKValues == null)
                    {
                        throw CreateKeyNotFoundException <TEntity>(keyName);
                    }
                }
                //- 1,2
                var ps = new ExecuteParameterCollection(keyName, entityOrPKValues);
                return(new WhereParameters(CreateWhere(engine, ps), ps));
            }
            else
            {//- 多个主键,4
                if (!type.IsArray)
                {
                    throw new NotSupportedException($"类型“{typeof(TEntity).FullName}”执行删除命令时,{nameof(entityOrPKValues)} 参数必须是一个数组。");
                }

                var array   = (Array)entityOrPKValues;
                var builder = new SqlBuilder(engine);
                var factory = engine.Provider.SqlFactory;
                builder.Where();
                foreach (var item in array)
                {
                    var itemType = item.GetType();
                    if (itemType.IsSimpleType())
                    {
                        throw new NotSupportedException($"类型“{typeof(TEntity).FullName}”包含多个主键,{nameof(entityOrPKValues)} 参数所有值都必须是一个复杂对象。");
                    }
                    else
                    {
                        var itemMapper = TypeMapper.Create(itemType);
                        builder.Or().BeginGroup();

                        foreach (var keyProp in mapper.KeyProperties)
                        {
                            var tmpKV = itemMapper[keyProp.Name]?.GetValue(item, true);
                            if (tmpKV == null)
                            {
                                throw CreateKeyNotFoundException <TEntity>(keyProp.Name);
                            }
                            builder.AndValue(keyProp.Name, tmpKV);
                        }
                        builder.EndGroup();
                    }
                }
                return(new WhereParameters(builder.WhereText, builder.Parameters));
            }
        }
Ejemplo n.º 8
0
Archivo: GA.cs Proyecto: sinxiaji/Aoite
        private static CompareResult Compare(string name, Type type, object t1, object t2)
        {
            type = type.GetNullableType();
            switch (Type.GetTypeCode(type))
            {
            case TypeCode.Object:
                if (t1 == null || t2 == null)
                {
                    goto default;
                }
                if (type.IsSubclassOf(DefineTypes.Exception) || type == DefineTypes.Exception)
                {
                    t1 = t1.ToString();
                    t2 = t2.ToString();
                    goto default;
                }
                if (type.IsArray)
                {
                    var a1 = t1 as Array;
                    var a2 = t2 as Array;
                    if (a1 == null || a2 == null)
                    {
                        goto default;
                    }
                    if (a1.Length != a2.Length)
                    {
                        return new CompareResult
                               {
                                   Name   = "数组长度",
                                   Value1 = a1.Length,
                                   Value2 = a2.Length
                               }
                    }
                    ;
                    for (int i = 0; i < a1.Length; i++)
                    {
                        var r = Compare(a1.GetValue(i), a2.GetValue(i));
                        if (r != null)
                        {
                            return(r);
                        }
                    }
                }
                else if (type.IsSubclassOf(DefineTypes.IDictionary))
                {
                    var a1 = t1 as IDictionary;
                    var a2 = t2 as IDictionary;
                    if (a1 == null || a2 == null)
                    {
                        goto default;
                    }
                    if (a1.Count != a2.Count)
                    {
                        return new CompareResult
                               {
                                   Name   = "字典大小",
                                   Value1 = a1.Count,
                                   Value2 = a2.Count
                               }
                    }
                    ;
                    foreach (DictionaryEntry item in a1)
                    {
                        if (!a2.Contains(item.Key))
                        {
                            return new CompareResult
                                   {
                                       Name   = "字典键",
                                       Value1 = item.Key,
                                       Value2 = null
                                   }
                        }
                        ;

                        var r = Compare(item.Value, a2[item.Key]);
                        if (r != null)
                        {
                            return(r);
                        }
                    }
                }
                else if (type.IsSubclassOf(DefineTypes.IEnumerable))
                {
                    var a1 = new ArrayList();
                    foreach (var item in t1 as IEnumerable)
                    {
                        a1.Add(item);
                    }
                    var a2 = new ArrayList();
                    foreach (var item in t2 as IEnumerable)
                    {
                        a2.Add(item);
                    }

                    if (a1.Count != a2.Count)
                    {
                        return new CompareResult
                               {
                                   Name   = "枚举大小",
                                   Value1 = a1.Count,
                                   Value2 = a2.Count
                               }
                    }
                    ;
                    for (int i = 0; i < a1.Count; i++)
                    {
                        var r = Compare(a1[i], a2[i]);
                        if (r != null)
                        {
                            return(r);
                        }
                    }
                }
                var mp = TypeMapper.Create(type);
                foreach (var p in mp.Properties)
                {
                    try
                    {
                        var v1 = p.GetValue(t1, false);
                        var v2 = p.GetValue(t2, false);
                        var r  = Compare(p.Property.Name, p.Property.PropertyType, v1, v2);
                        if (r != null)
                        {
                            return(null);
                        }
                    }
                    catch (Exception)
                    {
                        throw;
                    }
                }
                break;

            default:
                if (!Equals(t1, t2))
                {
                    return(new CompareResult
                    {
                        Name = name,
                        Value1 = t1,
                        Value2 = t2
                    });
                }
                break;
            }
            return(null);
        }