示例#1
0
        public bool Update <T>(IDbConnection connection, T entity, IDbTransaction transaction, int?commandTimeout, string keyName, Snapshotter.Snapshot snapshot, IEnumerable <string> properties) where T : class
        {
            IClassMapper classMap = SqlGenerator.Configuration.GetMap <T>();

            keyName = keyName ?? classMap.DefaultUpdateKeyName;

            DynamicParameters diff = null;

            if (snapshot != null && !classMap.IsPartialUpdateDisabled)
            {
                diff = snapshot.Diff();
                var upl = diff.ParameterNames.ToList <string>();
                if (upl.Count == 0)
                {
                    return(true);
                }
                properties = upl;
            }

            bool updated = classMap.OnUpdate(entity);

            if (updated && snapshot != null && !classMap.IsPartialUpdateDisabled)
            {
                diff = snapshot.Diff();
                var upl = diff.ParameterNames.ToList <string>();
                if (upl.Count == 0)
                {
                    return(true);
                }
                properties = upl;
            }

            IPredicate predicate = GetKeyPredicate <T>(classMap, entity, keyName);
            Dictionary <string, object> parameters = new Dictionary <string, object>();
            string            sql = SqlGenerator.Update(classMap, predicate, parameters, keyName, properties);
            DynamicParameters dynamicParameters = new DynamicParameters();

            var columns = classMap.Properties.Where(p => !(p.Ignored || p.IsReadOnly || p.IsInsertOnly || p.IsAnyKeyType(KeyType.Identity)) && (properties == null || properties.Contains(p.Name)));

            if (diff != null)
            {
                foreach (var property in diff.ParameterNames.Where(property => columns.Any(c => c.Name == property)))
                {
                    var val = ((SqlMapper.IParameterLookup)diff)[property];
                    dynamicParameters.Add(property, val);
                }
            }
            else
            {
                foreach (var property in ReflectionHelper.GetObjectValues(entity).Where(property => columns.Any(c => c.Name == property.Key)))
                {
                    dynamicParameters.Add(property.Key, property.Value);
                }
            }

            foreach (var parameter in parameters)
            {
                dynamicParameters.Add(parameter.Key, parameter.Value);
            }

            return(connection.Execute(sql, dynamicParameters, transaction, commandTimeout, CommandType.Text) > 0);
        }