private RelationshipType _DetermineRelationshipType(string tableToGenerate, TableMappingInfo mapping) { RelationshipType relationshipType; if (string.Equals(mapping.ReferenceTable, tableToGenerate, StringComparison.OrdinalIgnoreCase)) { if (mManyToManyMappingTablesCache.Contains(mapping.SourceTable)) { relationshipType = RelationshipType.ManyToMany; } else if (!mapping.OneToOneRelationship) { relationshipType = RelationshipType.ManyToOne; } else { relationshipType = RelationshipType.OneToOnePrinciple; } } else if (string.Equals(mapping.SourceTable, tableToGenerate, StringComparison.OrdinalIgnoreCase)) { relationshipType = mapping.OneToOneRelationship ? RelationshipType.OneToOneDependent : RelationshipType.OneToMany; } else { throw new InvalidOperationException("This should never happen"); } return(relationshipType); }
public IEnumerable <TableMappingInfo> GetTableMappingInfo(string tableName) { var sqlReader = _GetSqlDataReaderFromSqlCommand( string.Format( @"SELECT colUsage.TABLE_NAME AS [SourceTable], colUsage.CONSTRAINT_NAME AS [FKName], refColUsage.TABLE_NAME AS [ReferenceTable], CASE refConstraints.DELETE_RULE WHEN 'CASCADE' THEN 1 ELSE 0 END AS [IsCascadeDelete], ISNULL((SELECT 1 FROM (SELECT (SELECT COUNT(*) FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE pkCols WHERE pkCols.TABLE_NAME = colUsage.TABLE_NAME AND OBJECTPROPERTY(OBJECT_ID(pkCols.CONSTRAINT_NAME), 'IsPrimaryKey') = 1 ) AS [pkCount], (SELECT COUNT(*) FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE pkCols JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE fkCols ON pkCols.COLUMN_NAME = fkCols.COLUMN_NAME AND pkCols.TABLE_NAME = fkCols.TABLE_NAME AND fkCols.CONSTRAINT_NAME = colUsage.CONSTRAINT_NAME WHERE pkCols.TABLE_NAME = colUsage.TABLE_NAME AND OBJECTPROPERTY(OBJECT_ID(pkCols.CONSTRAINT_NAME), 'IsPrimaryKey') = 1 ) AS [fkPkCount] , (SELECT COUNT(*) FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE fkCols WHERE fkCols.TABLE_NAME = colUsage.TABLE_NAME AND fkCols.CONSTRAINT_NAME = colUsage.CONSTRAINT_NAME) AS [fkCounts] ) counts WHERE pkCount = fkPkCount AND fkCounts = fkPkCount), 0) AS [OneToOneRelationship] FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS colUsage JOIN INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS refConstraints ON refConstraints.CONSTRAINT_NAME = colUsage.CONSTRAINT_NAME JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS refColUsage ON refColUsage.CONSTRAINT_NAME = refConstraints.UNIQUE_CONSTRAINT_NAME WHERE colUsage.TABLE_NAME = '{0}' OR refColUsage.TABLE_NAME = '{0}'" , tableName)); var tableMappings = new List <TableMappingInfo>(); while (sqlReader.Read()) { var mappingInfo = new TableMappingInfo { SourceTable = sqlReader.GetString(0), FKName = sqlReader.GetString(1), ReferenceTable = sqlReader.GetString(2), IsCascadeDelete = sqlReader.GetInt32(3) == 1, OneToOneRelationship = sqlReader.GetInt32(4) == 1 }; tableMappings.Add(mappingInfo); } return(tableMappings .OrderBy(map => map.SourceTable) .ThenBy(map => map.ReferenceTable)); }