Exemplo n.º 1
0
        public static SqlTable AddForeignKey(this SqlTable table, string referredTableName, string singleFkColumnName, bool isNullable = false, string fkName = null)
        {
            var referredTableNameWithSchema = new SchemaAndTableName(referredTableName);

            var fk = new ForeignKeyRegistrationToTableWithUniqueKeySingleColumn(table, referredTableNameWithSchema, singleFkColumnName, isNullable, fkName);

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

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

            table.Properties.Add(fk);

            Prepare(table);

            return(table);
        }
        internal static void UniqueKeySingleColumn(DatabaseDefinition definition, SqlTable sqlTable, ForeignKeyRegistrationToTableWithUniqueKeySingleColumn fkRegistration)
        {
            var referredTable     = definition.GetTable(fkRegistration.ReferredTableName);
            var referredUniqueKey = GetReferredUniqueIndex(referredTable);

            CheckValidity(referredUniqueKey, fkRegistration.SingleFkColumnName);

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

            var pkColumn = referredUniqueKey.SqlColumns[0].SqlColumn;

            var col = new SqlColumn();

            pkColumn.CopyTo(col);

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

            col.Name = fkRegistration.SingleFkColumnName;

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

            var order = sqlTable.Columns.GetOrder(placeHolderColumn.Name);

            sqlTable.Columns.Remove(placeHolderColumn.Name);

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

            fk.ForeignKeyColumns.Add(new ForeignKeyColumnMap(col, pkColumn));
        }