创建两个表之间的关系

create relation between two tables

我正在尝试在两个 table 之间建立关系。 用户选择第一个 table (choice1) 然后选择第二个 table (choice2) 并选择第二个 table (field2) 中的字段。然后他给关系起一个名字(namerelationship)

我收到这个错误

Invalid field definition 'ForeignKey' in definition of index or relationship

string namerelationship = txtNameRelationship.Text;
string choice1 = cboTable1.SelectedItem.ToString();
string choice2 = cboTable2.SelectedItem.ToString();
string field2 = cboField2.SelectedItem.ToString();

Relation myrel = clsDataSource.mydb.CreateRelation(namerelationship,  choice1, choice2);
Field myfield = new Field();
myfield = myrel.CreateField(choice1);
myfield.ForeignName = "ForeignKey";
myrel.Fields.Append(myfield);
clsDataSource.mydb.Relations.Append(myrel);

当使用 DAO 的 Relation 对象时,您需要为第一个字段指定第一个 table 中现有字段的名称(通常这是主键),并为 ForeignName 属性 作为第一个 table.

外键的第二个 table 字段的名称

所以假设你有一个 table 部门

IDDepartment (integer, primary key)
Description (text, not null)

还有一个 table 员工

IDEmployee (integer, primary key)
Name (text not null)
IDDepartment (integer, foreign key to Department table)

部门和员工之间存在这种关系 table:一名员工在一个(且只有一个)部门工作。 (1 比 1)

那么你的代码应该是

string choice1 = "Department";
string choice2 = "Employee";
string fieldPK = "IDDepartment"; // It is the primary key of Department
string fieldFK = "IDDepartment"; // It is the foreign key in table Employee that links to the Department table
Relation myrel = clsDataSource.mydb.CreateRelation(namerelationship,  
                 choice1, choice2);
Field myfield = myrel.CreateField(fieldPK);
myfield.ForeignName = fieldFK;
myrel.Fields.Append(myfield);
clsDataSource.mydb.Relations.Append(myrel);

说真的建议大家尽快从DAO转成ADO.NET