I have a Foreign key on my database like:
CONSTRAINT [FK_Table1_Table2] FOREIGN KEY (Id) REFERENCES [Table2]([Id])
So wrote a small c# program to get the ForeignKeys
from my database shown below:
using (SqlConnection connection = new SqlConnection(connectionString.ConnectionString))
{
connection.Open();
DataTable getSchema = connection.GetSchema("Tables");
foreach (DataRow tableRow in getSchema.Rows)
{
String tableName = tableRow.Field<String>("TABLE_NAME");
DataTable fKeys = connection.GetSchema("ForeignKeys", new[] { database, "dbo", tableName });
foreach (DataRow keys in fKeys.Rows)
{
String tName = key.Field<String>("table_name");
}
}
}
This returns the name of the Table
the Foreign key is on (Table1)
but I cannot get the other name of the other table this foreign key references (Table2)
.
Is it possible to get the name of the other table in the foreign key constraint using c#?