private void UpdateTable(Type type) { IEnumerable <TableSchemaInformation> columns = TableColumns(type); var types = PostgreScriptGenerator.StaticDataMapper().Keys.ToList(); var props = type.GetProperties().Where(v => types.Contains(v.PropertyType)).ToList(); FindDifferenceColums(type, columns, props); }
public void FindDifferenceColums(Type type, IEnumerable <TableSchemaInformation> dbColumns, IEnumerable <PropertyInfo> entityProps) { StringBuilder addBuilder = new StringBuilder(); StringBuilder removeBuilder = new StringBuilder(); var dbColumsList = dbColumns as TableSchemaInformation[] ?? dbColumns.ToArray(); var dbColumnNames = dbColumsList.Select(v => v.column_name).ToList(); var dbColumnTypes = dbColumsList.Select(v => v.data_type).ToList(); var propertyInfos = entityProps as PropertyInfo[] ?? entityProps.ToArray(); var removeProps = dbColumnNames.Except(propertyInfos.Select(v => v.Name)).ToList(); var addProps = propertyInfos.Select(v => v.Name).Except(dbColumnNames).ToList(); foreach (var dbColumn in dbColumsList) { var entityProp = propertyInfos.FirstOrDefault(v => v.Name == dbColumn.column_name); if (entityProp == null) { continue; } DbColumnType propType = PostgreScriptGenerator.DataTypeMapper()[entityProp.PropertyType]; if (propType.Type == dbColumn.data_type && propType.IsNullable == IsNullableConverter(dbColumn.is_nullable)) { continue; } removeProps.Add(dbColumn.column_name); addProps.Add(entityProp.Name); } foreach (var propString in addProps) { var prop = entityProps.FirstOrDefault(v => v.Name == propString); string script = "ALTER TABLE \"" + type.Name + "\" ADD COLUMN IF NOT EXISTS \"" + propString + "\" " + PostgreScriptGenerator.StaticDataMapper()[prop.PropertyType]; if (!DataHelper.IsNullableType(prop.PropertyType)) { script += GenerateDefaultValue(type, prop); } script += ";"; addBuilder.AppendLine(script); } foreach (var propString in removeProps) { string script = "ALTER TABLE \"" + type.Name + "\" DROP COLUMN \"" + propString + "\";"; removeBuilder.AppendLine(script); } _connection.Execute(removeBuilder.ToString() + addBuilder); }