public static TableDefinition GetTableDefinition(Type modelType) { //Looks for PetaPoco's TableNameAtribute for the name of the table //If no attribute is set we use the name of the Type as the default convention var tableNameAttribute = modelType.FirstAttribute<TableNameAttribute>(); string tableName = tableNameAttribute == null ? modelType.Name : tableNameAttribute.Value; var tableDefinition = new TableDefinition {Name = tableName}; var objProperties = modelType.GetProperties().ToList(); foreach (var propertyInfo in objProperties) { //If current property has an IgnoreAttribute then skip it var ignoreAttribute = propertyInfo.FirstAttribute<IgnoreAttribute>(); if (ignoreAttribute != null) continue; //If current property has a ResultColumnAttribute then skip it var resultColumnAttribute = propertyInfo.FirstAttribute<ResultColumnAttribute>(); if (resultColumnAttribute != null) continue; //Looks for ColumnAttribute with the name of the column, which would exist with ExplicitColumns //Otherwise use the name of the property itself as the default convention var columnAttribute = propertyInfo.FirstAttribute<ColumnAttribute>(); string columnName = columnAttribute != null ? columnAttribute.Name : propertyInfo.Name; var columnDefinition = GetColumnDefinition(modelType, propertyInfo, columnName, tableName); tableDefinition.Columns.Add(columnDefinition); //Creates a foreignkey definition and adds it to the collection on the table definition var foreignKeyAttributes = propertyInfo.MultipleAttribute<ForeignKeyAttribute>(); if (foreignKeyAttributes != null) { foreach (var foreignKeyAttribute in foreignKeyAttributes) { var foreignKeyDefinition = GetForeignKeyDefinition(modelType, propertyInfo, foreignKeyAttribute, columnName, tableName); tableDefinition.ForeignKeys.Add(foreignKeyDefinition); } } //Creates an index definition and adds it to the collection on the table definition var indexAttribute = propertyInfo.FirstAttribute<IndexAttribute>(); if (indexAttribute != null) { var indexDefinition = GetIndexDefinition(modelType, propertyInfo, indexAttribute, columnName, tableName); tableDefinition.Indexes.Add(indexDefinition); } } return tableDefinition; }
public override string ToString() { var table = new TableDefinition{Name = TableName, SchemaName = SchemaName, Columns = Columns}; return string.Format(SqlSyntaxContext.SqlSyntaxProvider.Format(table)); }