private void GenerateUpdateSetClause(object entity, IEnumerable <string> fieldsToUpdate, EntityMetadata entityMetadata, IPropertyGetterDictionary getters, DbCommand cmd, StringBuilder commandText, ref bool hasEntityRowVersionField) { bool firstTime = true; foreach (var propertyName in fieldsToUpdate) { PropertyMetadata propMetadata = null; if (!entityMetadata.UpdatableProperties.TryGetValue(propertyName, out propMetadata)) { continue; } SqlFieldAttribute field = propMetadata.SqlField; if (!field.IsKey && !string.Equals(propertyName, DataService.SpecialFieldNames.CreatedByFieldName, StringComparison.OrdinalIgnoreCase) && !string.Equals(propertyName, DataService.SpecialFieldNames.CreatedDateFieldName, StringComparison.OrdinalIgnoreCase) ) { if (firstTime) { commandText.Append(" SET\n "); firstTime = false; } else { commandText.Append(",\n "); } if (string.Equals(propertyName, DataService.SpecialFieldNames.EntityRowVersionFieldName, StringComparison.OrdinalIgnoreCase)) { hasEntityRowVersionField = true; commandText.Append(this.DataService.EntityLiteProvider.StartQuote + propMetadata.SqlField.BaseColumnName + this.DataService.EntityLiteProvider.EndQuote).Append(" = ") .Append(this.DataService.EntityLiteProvider.StartQuote + propMetadata.SqlField.BaseColumnName + this.DataService.EntityLiteProvider.EndQuote).Append(" + 1"); } else if (propertyName == DataService.SpecialFieldNames.DbChangeNumberFieldName) { commandText.Append(this.DataService.EntityLiteProvider.StartQuote + propMetadata.SqlField.BaseColumnName + this.DataService.EntityLiteProvider.EndQuote).Append(" = ") .Append(DataService.EntityLiteProvider.GetNextValExpression(GetDbChangeNumberFullSequenceName())); } else { string parameterName; IDbDataParameter param = CreateParameter(propMetadata, propertyName, out parameterName); commandText.Append(this.DataService.EntityLiteProvider.StartQuote + field.BaseColumnName + this.DataService.EntityLiteProvider.EndQuote) .Append(" = ").Append(parameterName); object fieldValue = getters[propertyName](entity); SetValueToCommandParameter(entity, getters, propertyName, param); cmd.Parameters.Add(param); } } } }
private void GenerateUpdateWhereClauseWithPrimaryKeyAndEntityRowVersion(object entity, EntityMetadata entityMetadata, IPropertyGetterDictionary getters, DbCommand cmd, StringBuilder commandText, bool hasEntityRowVersionField) { bool firstTime = true; IEnumerable <string> whereFields = entityMetadata.PrimaryKeyPropertyNames; if (hasEntityRowVersionField) { whereFields = whereFields.Concat(new string[] { DataService.SpecialFieldNames.EntityRowVersionFieldName }); } foreach (string whereField in whereFields) { var property = entityMetadata.Properties[whereField]; SqlFieldAttribute field = property.SqlField; if (string.Equals(field.ColumnName, field.BaseColumnName, StringComparison.OrdinalIgnoreCase)) { string parameterName; IDbDataParameter parameter = CreateParameter(property, whereField, out parameterName); if (firstTime) { commandText.Append("\nWHERE\n "); firstTime = false; } else { commandText.Append("\n AND "); } commandText.Append(this.DataService.EntityLiteProvider.StartQuote + field.BaseColumnName + this.DataService.EntityLiteProvider.EndQuote) .Append(" = ").Append(parameterName); PropertyGetter getter; if (getters.TryGetValue(whereField, out getter)) { object parameterValue = getter(entity); parameter.Value = parameterValue == null ? DBNull.Value : parameterValue; } cmd.Parameters.Add(parameter); } } }
private DbCommand GenerateDeleteCommand(object entity) { try { if (entity == null) { throw new ArgumentNullException(nameof(entity)); } Type entityType = entity.GetType(); EntityMetadata entityMetadata = entityType.GetEntityMetadata(); if (entityMetadata == null) { throw new InvalidOperationException("cannot generate delete command for entity " + entityType.Name + " because it does not have metadata"); } string baseTable = entityMetadata.BaseTableName; if (string.IsNullOrEmpty(baseTable)) { throw new InvalidOperationException("cannot generate delete command for entity " + entityType.Name + " because it does not have a base table"); } if (entityMetadata.PrimaryKeyPropertyNames.Count == 0) { throw new InvalidOperationException("cannot generate delete command for entity " + entityType.Name + " because it does not have a primary key"); } IPropertyGetterDictionary getters = PropertyHelper.GetPropertyGetters(entityType); DbCommand cmd = DataService.EntityLiteProvider.CreateCommand(); StringBuilder commandText = new StringBuilder(); string fullTableName = entityMetadata.GetFullTableName(this.DataService.EntityLiteProvider.DefaultSchema, this.DataService.EntityLiteProvider.StartQuote, this.DataService.EntityLiteProvider.EndQuote); commandText.Append("\nDELETE FROM ").Append(fullTableName); bool firstTime = true; foreach (string fieldName in entityMetadata.PrimaryKeyPropertyNames) { var property = entityMetadata.Properties[fieldName]; SqlFieldAttribute field = property.SqlField; string parameterName; IDbDataParameter param = CreateParameter(property, fieldName, out parameterName); SetValueToCommandParameter(entity, getters, fieldName, param); cmd.Parameters.Add(param); if (firstTime) { commandText.Append("\nWHERE\n "); firstTime = false; } else { commandText.Append("\n AND "); } commandText.Append(this.DataService.EntityLiteProvider.StartQuote + field.BaseColumnName + this.DataService.EntityLiteProvider.EndQuote).Append(" = ").Append(parameterName); } cmd.CommandText = commandText.ToString(); return(cmd); } catch (Exception ex) { if (entity == null) { Log?.LogError(ex, "Error generating delete command"); } else { string primaryKey = entity.GetPrimaryKey().ToListString() ?? "'no id'"; string message = string.Format(CultureInfo.InvariantCulture, "Error generating delete command for entity of type {0} with primary key: {1}", entity.GetType().Name, primaryKey); #pragma warning disable CA2254 // Template should be a static expression Log?.LogError(ex, message); #pragma warning restore CA2254 // Template should be a static expression } throw; } }
public void AppendInsertStatement(object entity, DbCommand cmd, StringBuilder commandText) { if (entity == null) { throw new ArgumentNullException(nameof(entity)); } if (cmd == null) { throw new ArgumentNullException(nameof(cmd)); } if (commandText == null) { throw new ArgumentNullException(nameof(commandText)); } var entityType = entity.GetType(); var entityMetadata = entityType.GetEntityMetadata(); string fullTableName = entityMetadata.GetFullTableName(this.DataService.EntityLiteProvider.DefaultSchema, this.DataService.EntityLiteProvider.StartQuote, this.DataService.EntityLiteProvider.EndQuote); IPropertyGetterDictionary getters = entityType.GetPropertyGetters(); var entityRowVersionFieldName = DataService.SpecialFieldNames.EntityRowVersionFieldName; StringBuilder valuesText = new StringBuilder(); commandText.Append("\nINSERT INTO ").Append(fullTableName); bool firstTime = true; var sequenceVariable = DataService.EntityLiteProvider.SequenceVariable; var startQuote = this.DataService.EntityLiteProvider.StartQuote; var parameters = cmd.Parameters; var endQuote = this.DataService.EntityLiteProvider.EndQuote; var parameterPrefix = this.DataService.EntityLiteProvider.ParameterPrefix; foreach (var kv in entityMetadata.UpdatableProperties) { SqlFieldAttribute field = kv.Value.SqlField; //en PostgeSQL se manejan las secuencias de otra manera, como un autonumérico. // //if (field.SequenceName != null && sequenceVariable == null) continue; string propertyName = kv.Key; if (firstTime) { commandText.Append('('); valuesText.Append("\nVALUES ("); firstTime = false; } else { commandText.Append(", "); valuesText.Append(", "); } commandText.Append(startQuote).Append(field.BaseColumnName).Append(endQuote); if (propertyName == entityRowVersionFieldName) { valuesText.Append('1'); } else if (propertyName == DataService.SpecialFieldNames.DbChangeNumberFieldName) { valuesText.Append(DataService.EntityLiteProvider.GetNextValExpression(GetDbChangeNumberFullSequenceName())); } else if (field.SequenceName != null) { if (DataService.EntityLiteProvider.SequenceVariable != null) { valuesText.Append(DataService.EntityLiteProvider.SequenceVariable); } else { valuesText.Append(DataService.EntityLiteProvider.GetNextValExpression(field.SequenceName)); } } else { string parameterName; IDbDataParameter param = CreateParameter(kv.Value, propertyName, out parameterName); valuesText.Append(parameterName); SetValueToCommandParameter(entity, getters, propertyName, param); parameters.Add(param); } } commandText.Append(')'); valuesText.Append(')'); commandText.Append(valuesText.ToString()); }
private void AddModifiedFieldsPredicateToToUpdateWhereClause(IEnumerable <string> fieldsToUpdate, EntityMetadata entityMetadata, StringBuilder commandText) { var propertiesMetadata = new List <PropertyMetadata>(); foreach (var propertyName in fieldsToUpdate) { PropertyMetadata propMetadata = null; if (!entityMetadata.UpdatableProperties.TryGetValue(propertyName, out propMetadata)) { continue; } SqlFieldAttribute field = propMetadata.SqlField; if ((field.Size == Int32.MaxValue) && (DataService.EntityLiteProvider is inercya.EntityLite.Providers.OracleEntityLiteProvider)) { return; } if (!field.IsKey && !string.Equals(propertyName, DataService.SpecialFieldNames.CreatedByFieldName, StringComparison.OrdinalIgnoreCase) && !string.Equals(propertyName, DataService.SpecialFieldNames.CreatedDateFieldName, StringComparison.OrdinalIgnoreCase) && !string.Equals(propertyName, DataService.SpecialFieldNames.EntityRowVersionFieldName, StringComparison.OrdinalIgnoreCase) && !string.Equals(propertyName, DataService.SpecialFieldNames.ModifiedByFieldName, StringComparison.OrdinalIgnoreCase) && !string.Equals(propertyName, DataService.SpecialFieldNames.ModifiedDateFieldName, StringComparison.OrdinalIgnoreCase) && !string.Equals(propertyName, DataService.SpecialFieldNames.DbChangeNumberFieldName, StringComparison.OrdinalIgnoreCase) ) { propertiesMetadata.Add(propMetadata); } } if (propertiesMetadata.Count == 0) { return; } bool firstTime = true; commandText.Append("\n AND ("); foreach (var propMetadata in propertiesMetadata) { SqlFieldAttribute field = propMetadata.SqlField; string propertyName = propMetadata.PropertyInfo.Name; string parameterName = DataService.EntityLiteProvider.ParameterPrefix + propertyName; string fieldName = this.DataService.EntityLiteProvider.StartQuote + field.BaseColumnName + this.DataService.EntityLiteProvider.EndQuote; commandText.Append("\n "); if (firstTime) { firstTime = false; } else { commandText.Append("OR "); } if (propMetadata.SqlField.DbType == DbType.Xml) { commandText.Append("CAST (").Append(fieldName).Append(" AS nvarchar(max))"); commandText.Append(" <> "); commandText.Append("CAST (").Append(parameterName).Append(" AS nvarchar(max))"); } else { commandText.Append(fieldName).Append(" <> ").Append(parameterName); } commandText.Append(" OR ").Append(fieldName).Append(" IS NULL AND ").Append(parameterName).Append(" IS NOT NULL") .Append(" OR ").Append(fieldName).Append(" IS NOT NULL AND ").Append(parameterName).Append(" IS NULL"); } commandText.Append("\n )"); }
/// <summary> /// 解析Model类 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="obj">Model类</param> /// <returns></returns> public static TableInfo GetDataFields <T>(T obj = null) where T : class, new() { Type type; if (obj == null) { type = typeof(T); } else { type = obj.GetType(); } TableInfo tableInfo = new TableInfo(); //type.Name 即为Class名称 tableInfo.TableName = type.Name; //Model字段List tableInfo.Colums = new List <ColumInfo>(); //判断是否存在缓存中 object obj2 = Cache.ReadCache(type.Name); if (obj2 != null) { tableInfo = (TableInfo)obj2; } else { //读取Model下所有的公共字段(属性) PropertyInfo[] properties = type.GetProperties(); tableInfo.Props = properties; PropertyInfo[] array = properties; for (int i = 0; i < array.Length; i++) { PropertyInfo propertyInfo = array[i]; //获取SqlFieldAttribute特性 SqlFieldAttribute[] array2 = (SqlFieldAttribute[])propertyInfo.GetCustomAttributes(typeof(SqlFieldAttribute), false); ColumInfo columInfo = new ColumInfo(); columInfo.ColName = propertyInfo.Name; columInfo.ColType = propertyInfo.PropertyType; if (array2 != null && array2.Length > 0) { //存在SqlFieldAttribute特性就读取 SqlFieldAttribute sqlFieldAttribute = array2[0]; columInfo.ColCanWrite = !sqlFieldAttribute.Identity; columInfo.Identity = sqlFieldAttribute.Identity; columInfo.ColIsKey = sqlFieldAttribute.Key; columInfo.ColIsIgnore = sqlFieldAttribute.Ignore; } else { //不存在则默认 columInfo.ColIsKey = false; columInfo.ColCanWrite = true; columInfo.ColIsIgnore = false; columInfo.Identity = false; } tableInfo.Colums.Add(columInfo); } //添加到缓存 Cache.AddCache(tableInfo.TableName, tableInfo, DateTime.Now.AddMonths(1)); } return(tableInfo); }