Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the table a foreign key refers to

Tags:

c#

sql-server

smo

I have an small question I didn't found an answer yet: how do I get in c# and using Microsoft.SqlServer.Smo the table a foreign key column is referring to?

foreach (Column column in currentTable.Columns) {
        if (column.IsForeignKey) {
                 //GET TABLE FOREIGN KEY REFERS TO
          }
   }
like image 942
Ronnie Avatar asked Jan 19 '09 19:01

Ronnie


2 Answers

You should start from the table itself, and enumerate all of it's foreign keys. Sample code:

foreach (ForeignKey key in currentTable.ForeignKeys)
{
    foreach (ForeignKeyColumn column in key.Columns)
    {
        Console.WriteLine("Column: {0} is a foreign key to Table: {1}",column.Name,key.ReferencedTable);
    }
}

EDIT: Small change. In second foreach loop use foreach (ForeignKeyColumn column in key.Columns) (I had it foreach (Column column in key.Columns) before, and that's wrong. My mistake.)

like image 180
BFree Avatar answered Sep 20 '22 01:09

BFree


use SMO dll

http://msdn.microsoft.com/en-us/library/microsoft.sqlserver.management.smo.table.aspx

like image 39
Marco Avatar answered Sep 24 '22 01:09

Marco