0

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#?

jhpratt
  • 6,841
  • 16
  • 40
  • 50
JKennedy
  • 18,150
  • 17
  • 114
  • 198
  • I don't think you can use `GetSchema` in order to extract the info you want. [This](https://msdn.microsoft.com/en-us/library/ms254969%28v=vs.110%29.aspx) is all you can get for *Foreign Keys* and the referenced table is not part of it. – Giorgos Betsos Oct 26 '15 at 22:05
  • 1
    @Servy This is not a duplicate question. The answer makes use of the same SQL command, but the question is different. This is asking about C# the other is SQL. How can that be a duplicate question? – xr280xr Aug 09 '19 at 22:41

0 Answers0