【问题标题】:create relation between two tables创建两个表之间的关系
【发布时间】:2016-10-23 19:25:36
【问题描述】:

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

我收到此错误

索引或关系定义中的字段定义“ForeignKey”无效

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

【问题讨论】:

  • 您能解释一下您在使用上述代码时遇到了什么问题吗?
  • 我用我的错误更新了它
  • 你为什么不对下面的C# DataSource.CreateRelation 进行谷歌搜索,看来你目前这样做不正确
  • 您已使用比 ADO 更早的 DAO 标记了此问题。您使用的是哪个库?
  • 我在这个项目中使用 DAO

标签: c# dao


【解决方案1】:

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

所以假设你有一个带有

的部门表
IDDepartment (integer, primary key)
Description (text, not null)

还有一张员工表

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

Department 和 Employee 表之间存在这种关系:员工在一个(并且只有一个)部门工作。 (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

【讨论】:

  • 谢谢。按照您的解释并使我的变量更加清晰,我成功地建立了关系。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-25
  • 1970-01-01
  • 1970-01-01
  • 2019-08-08
  • 1970-01-01
  • 2013-07-01
相关资源
最近更新 更多