public InsertQueryType <T> Insert(object obj, bool replace = false) { var properties = obj.GetType().GetProperties(); foreach (var property in properties) { string propertyName = property.Name; object value = property.GetValue(obj); bool isAutoincrement = AutoIncrementAttribute.IsAutoIncrement(property); if (value != null && !isAutoincrement) { Insert(propertyName, value); } } if (replace) { ShouldReplace = true; } return(this); }
public override string GenerateQuery(Type type) { string tableName = TableAttribute.GetAttributeTable(type); StringBuilder queryBuilder = new StringBuilder($"CREATE TABLE IF NOT EXISTS `{tableName}` ("); List <string> tableFields = new List <string>(); List <string> primaryKeys = new List <string>(); var properties = type.GetProperties(); foreach (var property in properties) { string propertyTypeName = property.PropertyType.Name; string propertyName = property.Name; string sqlType = null; try { sqlType = CSharpTypesToSqlTypesDictionary[propertyTypeName]; } catch (Exception) { throw new NotSupportedException("The C# type " + propertyTypeName + " is not supported for C# to SQL conversion."); } string dataType = sqlType; int?columnLength = ColumnLengthAttribute.GetAttributeColumnLength(property); if (columnLength != null || propertyTypeName == "String") { dataType = string.Format(dataType, columnLength ?? 50); } bool isAutoIncrement = AutoIncrementAttribute.IsAutoIncrement(property); if (isAutoIncrement) { if (Database.DatabaseDriver is MySQLoo) { dataType += " AUTO_INCREMENT"; } } bool isPrimaryKey = PrimaryKeyAttribute.IsPrimaryKey(property); if (isPrimaryKey) { // Check if is SQLite/MySQL if (Database.DatabaseDriver is MySQLoo) { primaryKeys.Add(propertyName); } else if (Database.DatabaseDriver is SQLite) { dataType += " PRIMARY KEY"; } } tableFields.Add($"{propertyName} {dataType}"); } queryBuilder.Append(string.Join(", ", tableFields)); if (primaryKeys.Count > 0) { queryBuilder.Append(", PRIMARY KEY ("); queryBuilder.Append(string.Join(", ", primaryKeys)); queryBuilder.Append(")"); } queryBuilder.Append(");"); return(queryBuilder.ToString()); }