This example shows how you can use the ForeignName, ForeignTable, and Table properties when you create a relationship between two existing tables — in this case, Table1 (the primary table) and Table2 (the foreign table) in the specified database. Field1 is the primary key in Table1 and Field2 is a foreign key in Table2. The relationship is one-to-many and referential integrity is enforced.
CdbDBEngine dbeng;
CdbDatabase dbsDefault;
CdbField fldLocal;
CdbRelation relForeign;
// Get database
dbsDefault = dbeng.OpenDatabase(_T("Northwind.mdb"));
// Create new relationship and set its properties.
relForeign = dbsDefault.CreateRelation(_T("MyRelation"));
relForeign.SetTable(_T("Table1"));
relForeign.SetForeignTable(_T("Table2"));
// Create field and set its properties.
fldLocal = relForeign.CreateField(_T("Field1"));
fldLocal.SetForeignName(_T("Field2"));
// Append field to relation and relation to database.
relForeign.Fields.Append(fldLocal);
dbsDefault.Relations.Append(relForeign);
dbsDefault.Close();