예제 #1
0
        public bool Update <T>(IDbConnection connection, T entity, IDbTransaction transaction, int?commandTimeout, bool ignoreAllKeyProperties = false) where T : class
        {
            IClassMapper classMap  = SqlGenerator.Configuration.GetMap <T>();
            IPredicate   predicate = GetKeyPredicate <T>(classMap, entity);
            Dictionary <string, object> parameters = new Dictionary <string, object>();
            string sql = SqlGenerator.Update(classMap, predicate, parameters, ignoreAllKeyProperties);

            var columns = ignoreAllKeyProperties
                ? classMap.Properties.Where(p => !(p.Ignored || p.IsReadOnly) && p.KeyType == KeyType.NotAKey)
                : classMap.Properties.Where(p => !(p.Ignored || p.IsReadOnly || p.KeyType == KeyType.Identity || p.KeyType == KeyType.TriggerIdentity || p.KeyType == KeyType.Assigned));

            DynamicParameters dynamicParameters = GetDynamicParameters(parameters);

            foreach (var property in ReflectionHelper.GetObjectValues(entity).Where(property => columns.Any(c => c.Name == property.Key)))
            {
                var parameter = ReflectionHelper.GetParameter(typeof(T), SqlGenerator, property.Key, property.Value);
                dynamicParameters.Add(parameter.Name, parameter.Value, parameter.DbType,
                                      parameter.ParameterDirection, parameter.Size, parameter.Precision,
                                      parameter.Scale);
            }



            LastExecutedCommand = sql;
            return(connection.Execute(sql, dynamicParameters, transaction, commandTimeout, CommandType.Text) > 0);
        }
예제 #2
0
        public override string GetSql(ISqlGenerator sqlGenerator, IDictionary <string, object> parameters)
        {
            string columnName = GetColumnName(typeof(T), sqlGenerator, PropertyName);

            if (Value == null)
            {
                return(string.Format("({0} IS {1}NULL)", columnName, Not ? "NOT " : string.Empty));
            }

            if (Value is IEnumerable enumerable && !(Value is string))
            {
                if (Operator != Operator.Eq)
                {
                    throw new ArgumentException("Operator must be set to Eq for Enumerable types");
                }

                List <string> @params = new List <string>();
                foreach (var value in enumerable)
                {
                    var    p = ReflectionHelper.GetParameter(typeof(T), sqlGenerator, PropertyName, value);
                    string valueParameterName = parameters.SetParameterName(p, sqlGenerator.Configuration.Dialect.ParameterPrefix);
                    @params.Add(valueParameterName);
                }

                string paramStrings = @params.Aggregate(new StringBuilder(), (sb, s) => sb.Append((sb.Length != 0 ? ", " : string.Empty) + s), sb => sb.ToString());
                return(string.Format("({0} {1}IN ({2}))", columnName, Not ? "NOT " : string.Empty, paramStrings));
            }

            var    parameter     = ReflectionHelper.GetParameter(typeof(T), sqlGenerator, PropertyName, Value);
            string parameterName = parameters.SetParameterName(parameter, sqlGenerator.Configuration.Dialect.ParameterPrefix);

            return(string.Format("({0} {1} {2})", columnName, GetOperatorString(), parameterName));
        }
예제 #3
0
        protected virtual DynamicParameters AddParameter <T>(T entity, DynamicParameters parameters, IMemberMap prop, bool useColumnAlias = false)
        {
            var propValue = prop.GetValue(entity);
            var parameter = ReflectionHelper.GetParameter(typeof(T), SqlGenerator, prop.Name, propValue);
            var alias     = GetSimpleAliasFromColumnAlias(parameter.Name);
            var name      = useColumnAlias ? string.IsNullOrEmpty(alias) ? parameter.Name : alias : parameter.Name;

            parameters ??= new DynamicParameters();

            if (prop.MemberInfo.DeclaringType == typeof(bool) || (prop.MemberInfo.DeclaringType.IsGenericType && prop.MemberType.GetGenericTypeDefinition() == typeof(Nullable <>) && prop.MemberInfo.DeclaringType.GetGenericArguments()[0] == typeof(bool)))
            {
                var value = (bool?)propValue;
                if (!value.HasValue)
                {
                    parameters.Add(name, value, parameter.DbType,
                                   parameter.ParameterDirection, parameter.Size, parameter.Precision,
                                   parameter.Scale);
                }
                else
                {
                    parameters.Add(name, value.Value ? 1 : 0, parameter.DbType,
                                   parameter.ParameterDirection, parameter.Size, parameter.Precision,
                                   parameter.Scale);
                }
            }
            else
            {
                parameters.Add(name, parameter.Value, parameter.DbType,
                               parameter.ParameterDirection, parameter.Size, parameter.Precision,
                               parameter.Scale);
            }

            return(parameters);
        }
예제 #4
0
        public override string GetSql(ISqlGenerator sqlGenerator, IDictionary <string, object> parameters)
        {
            string    columnName    = GetColumnName(typeof(T), sqlGenerator, PropertyName);
            Parameter parameter1    = ReflectionHelper.GetParameter(typeof(T), sqlGenerator, PropertyName, Value.Value1);
            Parameter parameter2    = ReflectionHelper.GetParameter(typeof(T), sqlGenerator, PropertyName, Value.Value2);
            string    propertyName1 = parameters.SetParameterName(parameter1, sqlGenerator.Configuration.Dialect.ParameterPrefix);
            string    propertyName2 = parameters.SetParameterName(parameter2, sqlGenerator.Configuration.Dialect.ParameterPrefix);

            return(string.Format("({0} {1}BETWEEN {2} AND {3})", columnName, Not ? "NOT " : string.Empty, propertyName1, propertyName2));
        }
예제 #5
0
        public void Insert <T>(IDbConnection connection, IEnumerable <T> entities, IDbTransaction transaction, int?commandTimeout) where T : class
        {
            IClassMapper classMap              = SqlGenerator.Configuration.GetMap <T>();
            var          notKeyProperties      = classMap.Properties.Where(p => p.KeyType != KeyType.NotAKey);
            var          triggerIdentityColumn = classMap.Properties.SingleOrDefault(p => p.KeyType == KeyType.TriggerIdentity);

            var parameters = new List <DynamicParameters>();

            foreach (var e in entities)
            {
                foreach (var column in notKeyProperties)
                {
                    if (column.KeyType == KeyType.Guid && (Guid)column.GetValue(e) == Guid.Empty)
                    {
                        Guid comb = SqlGenerator.Configuration.GetNextGuid();
                        column.SetValue(e, comb);
                    }
                }

                var dynamicParameters = new DynamicParameters();
                foreach (
                    var prop in
                    e.GetType()
                    .GetProperties(BindingFlags.GetProperty | BindingFlags.Instance | BindingFlags.Public)
                    .Where(p => triggerIdentityColumn == null || p.Name != triggerIdentityColumn.Name)
                    )
                {
                    var propValue = prop.GetValue(e, null);

                    var parameter = ReflectionHelper.GetParameter(typeof(T), SqlGenerator, prop.Name, propValue);
                    dynamicParameters.Add(parameter.Name, parameter.Value, parameter.DbType,
                                          parameter.ParameterDirection, parameter.Size, parameter.Precision,
                                          parameter.Scale);
                }

                if (triggerIdentityColumn != null)
                {
                    // defaultValue need for identify type of parameter
                    var defaultValue = typeof(T).GetProperty(triggerIdentityColumn.Name).GetValue(e, null);
                    dynamicParameters.Add("IdOutParam", direction: ParameterDirection.Output, value: defaultValue);
                }

                parameters.Add(dynamicParameters);
            }

            string sql = SqlGenerator.Insert(classMap);

            LastExecutedCommand = sql;
            connection.Execute(sql, parameters, transaction, commandTimeout, CommandType.Text);
        }
예제 #6
0
        public override string GetSql(ISqlGenerator sqlGenerator, IDictionary <string, object> parameters)
        {
            var columnName = GetColumnName(typeof(T), sqlGenerator, PropertyName);

            var @params = new List <string>();

            foreach (var item in Collection)
            {
                var p = ReflectionHelper.GetParameter(typeof(T), sqlGenerator, PropertyName, item);
                @params.Add(parameters.SetParameterName(p, sqlGenerator.Configuration.Dialect.ParameterPrefix));
            }

            var commaDelimited = string.Join(",", @params);

            return($@"({columnName} {GetIsNotStatement(Not)} IN ({commaDelimited}))");
        }
예제 #7
0
        public dynamic Insert <T>(IDbConnection connection, T entity, IDbTransaction transaction, int?commandTimeout) where T : class
        {
            IClassMapper      classMap = SqlGenerator.Configuration.GetMap <T>();
            List <IMemberMap> nonIdentityKeyProperties = classMap.Properties.Where(p => p.KeyType == KeyType.Guid || p.KeyType == KeyType.Assigned).ToList();
            var identityColumn        = classMap.Properties.SingleOrDefault(p => p.KeyType == KeyType.Identity);
            var triggerIdentityColumn = classMap.Properties.SingleOrDefault(p => p.KeyType == KeyType.TriggerIdentity);

            foreach (var column in nonIdentityKeyProperties)
            {
                if (column.KeyType == KeyType.Guid && (Guid)column.GetValue(entity) == Guid.Empty)
                {
                    Guid comb = SqlGenerator.Configuration.GetNextGuid();
                    column.SetValue(entity, comb);
                }
            }

            var dynamicParameters = new DynamicParameters();

            foreach (var prop in entity.GetType().GetProperties(BindingFlags.GetProperty | BindingFlags.Instance | BindingFlags.Public)
                     .Where(p => triggerIdentityColumn == null || p.Name != triggerIdentityColumn.Name))
            {
                var propValue = prop.GetValue(entity, null);
                var parameter = ReflectionHelper.GetParameter(typeof(T), SqlGenerator, prop.Name, propValue);
                dynamicParameters.Add(parameter.Name, parameter.Value, parameter.DbType,
                                      parameter.ParameterDirection, parameter.Size, parameter.Precision,
                                      parameter.Scale);
            }

            IDictionary <string, object> keyValues = new ExpandoObject();
            string sql = SqlGenerator.Insert(classMap);

            LastExecutedCommand = sql;
            if (identityColumn != null)
            {
                object result;
                if (SqlGenerator.SupportsMultipleStatements())
                {
                    sql += SqlGenerator.Configuration.Dialect.BatchSeperator + SqlGenerator.IdentitySql(classMap);
                    LastExecutedCommand = sql;
                    result = connection.QuerySingle(identityColumn.MemberType, sql, entity, transaction, commandTimeout, CommandType.Text);
                }
                else
                {
                    connection.Execute(sql, dynamicParameters, transaction, commandTimeout, CommandType.Text);
                    sql = SqlGenerator.IdentitySql(classMap);
                    LastExecutedCommand += string.Format("{0}{0}{1}", Environment.NewLine, sql);
                    result = connection.QuerySingle(identityColumn.MemberType, sql, entity, transaction, commandTimeout, CommandType.Text);
                }

                var typedResult = Convert.ChangeType(result, identityColumn.MemberType);
                keyValues.Add(identityColumn.Name, typedResult);
                identityColumn.SetValue(entity, typedResult);
            }
            else if (triggerIdentityColumn != null)
            {
                dynamicParameters = new DynamicParameters();
                foreach (var prop in entity.GetType().GetProperties(BindingFlags.GetProperty | BindingFlags.Instance | BindingFlags.Public)
                         .Where(p => p.Name != triggerIdentityColumn.Name))
                {
                    dynamicParameters.Add(prop.Name, prop.GetValue(entity, null));
                }

                // defaultValue need for identify type of parameter
                var defaultValue = entity.GetType().GetProperty(triggerIdentityColumn.Name).GetValue(entity, null);
                dynamicParameters.Add("IdOutParam", direction: ParameterDirection.Output, value: defaultValue);

                connection.Execute(sql, dynamicParameters, transaction, commandTimeout, CommandType.Text);
                var value = dynamicParameters.Get <object>(SqlGenerator.Configuration.Dialect.ParameterPrefix + "IdOutParam");
                keyValues.Add(triggerIdentityColumn.Name, value);
                triggerIdentityColumn.SetValue(entity, value);
            }
            else
            {
                connection.Execute(sql, dynamicParameters, transaction, commandTimeout, CommandType.Text);
            }

            foreach (var column in nonIdentityKeyProperties)
            {
                keyValues.Add(column.Name, column.GetValue(entity));
            }

            if (keyValues.Count == 1)
            {
                return(keyValues.First().Value);
            }

            return(keyValues);
        }