public T Get <T>(object id, string tableName = null, int?commandTimeout = null) where T : class { IClassMapper classMapper = ClassMapperFactory.GetMapper <T>(tableName); KeyConditionResult keyConditionResult = SqlGenerator.GetKeyConditionById(classMapper, id); SqlConvertResult sqlConvertResult = SqlGenerator.Select(classMapper, keyConditionResult.Sql, null, keyConditionResult.Parameters, false); T result = DbConnection.Query <T>(sqlConvertResult.Sql, sqlConvertResult.Parameters, DbTransaction, true, commandTimeout, CommandType.Text).SingleOrDefault(); if (result == null) { return(null); } IPropertyMap persistedMap = classMapper.GetPersistedMap(); if (persistedMap != null) { persistedMap.PropertyInfo.SetValue(result, true, null); } IPropertyMap propertyChangedListMap = classMapper.GetPropertyChangedListMap(); if (propertyChangedListMap != null) { IList <string> changedList = propertyChangedListMap.PropertyInfo.GetValue(result, null) as IList <string>; if (changedList != null) { changedList.Clear(); } } return(result); }
public virtual SqlConvertResult Update(IClassMapper classMapper, string condition, DynamicParameters dynamicParameters, object entity = null) { if (dynamicParameters == null) { throw new ArgumentNullException("dynamicParameters"); } var columnMaps = classMapper.GetColumnMaps(); if (!columnMaps.Any()) { throw new ArgumentException("没有被映射的列。"); } if (entity != null) { IPropertyMap propertyChangedListMap = classMapper.GetPropertyChangedListMap(); if (propertyChangedListMap != null) { IList <string> propertyChangedList = propertyChangedListMap.PropertyInfo.GetValue(entity, null) as IList <string>; if (propertyChangedList != null && propertyChangedList.Count > 0) { propertyChangedList = propertyChangedList.Distinct().ToList(); IList <IPropertyMap> propertyMaps = new List <IPropertyMap>(); foreach (string name in propertyChangedList) { if (string.IsNullOrWhiteSpace(name)) { continue; } IPropertyMap propertyMap = columnMaps.FirstOrDefault(m => m != null && string.Compare(m.Name, name.Trim(), StringComparison.OrdinalIgnoreCase) == 0); if (propertyMap != null) { propertyMaps.Add(propertyMap); } } columnMaps = propertyMaps; } } } SqlConvertResult result = SqlConvert(classMapper, condition, dynamicParameters); var setSql = columnMaps.Select(p => string.Format("{0} = {1}{2}", GetColumnName(classMapper, p, false), DbProvider.ParameterPrefix, p.Name)); string updateSql = string.Format("UPDATE {0} SET {1} WHERE {2}", GetTableName(classMapper), setSql.AppendStrings(), result.Sql); result.Sql = updateSql; return(result); }