我可以在 C# 中找到直接表外键,如下所示:
foreach (ForeignKey key in CurrentTable.ForeignKeys) {
Console.WriteLine("FK:" + key.ReferencedTable);
}
多对多关系的经典表示是通过中间表实现的,该中间表与两个主表具有一对多关系,因此表之间没有直接链接具有多对多关系。
目前,我尝试找到多对多关系检查我正在分析的表是否只有两列,并且两列都是不同表的外键(在这种情况下,我将其识别为中间表)。
这不是最好的解决方案,因为有时中间表还包含其他列。
以编程方式找到这种多对多关系的最佳方法是什么?
I can find a direct table foreign key in c# like:
foreach (ForeignKey key in CurrentTable.ForeignKeys) {
Console.WriteLine("FK:" + key.ReferencedTable);
}
The classic representation for a many to many relationship is achieved via an intermediate table that has a one to many relation to the two principal tables so there is not a direct link between the tables that have the many2many relation.
For the moment I try to find the many to many relation checking if the table I am analyzing has only two columns and both colums are foreign keys to different tables (in that case I recognise this as the intermediate table).
This is not the best solution as sometimes the intermediate table carries also other columns.
What would the best way to find this many2many relation programmatically?
发布评论
评论(4)
作为附加标准,您可以使用以下事实:在许多情况下,两个外键中的一对代表连接/中间表的主键。
As additional criteria you could use the fact that in many cases the couple of the two foreign keys represents the primary key of the join/intermediate table.
您似乎已经提出了自己的解决方案。 与其搜索具有两个引用其他不同表的外键并且没有其他列的表,只需删除短语“并且没有其他列”即可。
换句话说,查找“具有两个引用其他不同表的外键的表”。
You seem to have posited your own solution. Rather than searching for tables that have two foreign keys referencing other distinct tables and with no other columns, just delete the phrase "and with no other columns".
In other words, look for "tables that have two foreign keys referencing other distinct tables".
该语句查找所有至少具有两个外键列的表
This statement finds all tables with at least two foreign key columns
如果一个表有两个不同表的外键列,那么它肯定代表了表之间的多对多关系。 表具有其他列的事实仅意味着表(实体)之间的关系由额外的属性进一步限定。 看一下下图中的示例:
在上面的示例中,产品和账单之间存在多对多关系。 交集表还将具有描述性属性,例如“数量”、“礼品包装”等。这并不能消除首先存在多对多关系的事实。 这些表看起来像这样
If a table has foreign key columns to two different tables, then it definitely represents the many to many relationship between the tables. The fact that the table has other columns only means that the relationship between the tables(entities) is further qualified by the extra attributes. Have a look at the example in the figure below:
In the example above there is a many to many relationship between product and bill. The intersection table will also have descriptive attributes like 'quantity', 'gift wrap' etc.. That does not take away the fact that there is a many to many relationship in the first place. The tables would look like this