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);
}
}
}