Ejemplo n.º 1
0
        public static SqlTable AddForeignKey(this SqlTable table, string referredTableName, List <ColumnReference> map, bool isNullable = false, string fkName = null)
        {
            var referredTableNameWithSchema = new SchemaAndTableName(referredTableName);

            var fk = new ForeignKeyRegistrationToReferredTable(table, referredTableNameWithSchema, isNullable, fkName, map);

            table.Properties.Add(fk);

            var mapColumnNames = string.Join("_", map.ConvertAll(m => m.ColumnName));

            var placeHolderColumnName = $"*{referredTableNameWithSchema}.{mapColumnNames}.{table.Columns.Count.ToString("D", CultureInfo.InvariantCulture)}";

            table.Columns.Add(new SqlColumnFKRegistration(placeHolderColumnName, fk));

            Prepare(table);

            return(table);
        }
        public static void ReferredTable(DatabaseDefinition definition, SqlTable sqlTable, ForeignKeyRegistrationToReferredTable fkRegistration)
        {
            var referredTable = definition.GetTable(fkRegistration.ReferredTableName);

            var fk = ReplaceFKRegistrationWithNewFK(sqlTable, fkRegistration, referredTable);

            var placeHolderColumn = sqlTable.Columns.OfType <SqlColumnFKRegistration>().FirstOrDefault(c => c.FKRegistration == fkRegistration);
            var order             = sqlTable.Columns.GetOrder(placeHolderColumn.Name);

            sqlTable.Columns.Remove(placeHolderColumn.Name);

            foreach (var fkGroup in fkRegistration.Map)
            {
                var col = new SqlColumn();
                referredTable.Columns[fkGroup.ReferredColumnName].CopyTo(col);

                col.Table = sqlTable;
                col.Types.SetAllNullable(fkRegistration.IsNullable);

                col.Name = fkGroup.ColumnName;

                sqlTable.Columns.Add(col.Name, col, order++);

                fk.ForeignKeyColumns.Add(new ForeignKeyColumnMap(col, referredTable[fkGroup.ReferredColumnName]));
            }
        }