Q:

Retrieve table relationships from MS Access DB using C#

I am using C# with MS Access 2010.  I need to retrieve the table relationships from the DB in order to determine the relationships between entities and use them in my C# code. 
I need the same functionality for SQL Server database also. 
Is there a way to do this using C# and .NET 3.0/ 3.5/ 4.0? 
Appreciate your time. 
Thanks,
Mahesh

A:

This is the code I used to retrieve the foreign key constraints (the relationships, if you prefer).  TableSchema, ForeignKey and ForeignKeyColumn are my own classes, where I store the result.  The point is to use the GetOleDbSchemaTable method of the OleDbConnection:
private static void RetrieveForeignKeyInfo(OleDbConnection cnn, TableSchema tableSchema, Func<string, string> prepareColumnNameForMapping)
{
    string[] fkRestrictions = new string[] { null, null, null, null, null, tableSchema. TableName };
    using (DataTable dtForeignKeys = cnn. GetOleDbSchemaTable(OleDbSchemaGuid. Foreign_Keys, fkRestrictions)) {
        ForeignKey foreignKey = null;
        string constraintName = "";
        foreach (DataRow row in dtForeignKeys. Rows) {
            string newConstraintName = (string)row["FK_NAME"];
            if (newConstraintName ! = constraintName) {
                constraintName = newConstraintName;
                foreignKey = new ForeignKey();
                foreignKey. MasterTableName = (string)row["PK_TABLE_NAME"];
                tableSchema. ForeignKeys. Add(foreignKey);
            }
            var foreignKeyColumn = new ForeignKeyColumn();
            foreignKeyColumn. DetailColumnName = (string)row["FK_COLUMN_NAME"];
            foreignKeyColumn. MasterColumnName = (string)row["PK_COLUMN_NAME"];
            foreignKeyColumn. DetailColumnNameForMapping = prepareColumnNameForMapping(foreignKeyColumn. DetailColumnName);
            foreignKeyColumn. MasterColumnNameForMapping = prepareColumnNameForMapping(foreignKeyColumn. MasterColumnName);
            foreignKey. Columns. Add(foreignKeyColumn);
        }
    }
}

