可疑的 SQL 关系
Questionable SQL Relationship
我正在学习 pluralsight 课程,该课程目前正在使用 entity framework 代码优先方法构建 MVC 应用程序。我对项目使用的数据库架构感到困惑。
如您所见,Securities 与其相关的 tables 之间的关系似乎是一对一的,但是当我意识到没有外键来关联这两个子项时,混乱就来了- tables 并且它们似乎共享相同的主键列。
之前的视频对证券模型 class 进行了抽象,以便 "Stock" 和 "MutualFund" 模型 class 继承它并包含所有相关数据。然而,对我来说,似乎可以使用几个外键来完成同样的事情。
我想我的问题是这种链接 table 的方法在 SQL 或 EF 中是否有任何有用的用途?在我看来,为了为一个 table 创建一个新记录,所有 table 都需要一个新记录,这是我真正感到困惑的地方。
在 ORM 和 EF 术语中,此设置称为 "Table per Type" 继承范例,其中每个子table class,一个基础 class table,子class和基class共享主键。
例如在这种情况下,Securities_Stock
和 Securities_MutualFund
是 Securities
基础 class / table 的两个子 class(可能是抽象的)。
关系将是 0..1 (subclass) to 1 (base class)
- 即每个 table Securities
行仅存在 Securities_MutualFund
或 Securities_Stock
中的记录之一。
基数 table 上也经常有一个鉴别器列来指示子class table 到 join
到哪个,但这似乎不是这里的案例。
使用外键在子 class 与基 table 之间强制执行引用完整性也很常见。
回答你的问题,之所以两个subclass instance
table之间没有FK是因为每个instance
(有唯一的Id)只会出现在子 class table 之一中 - 相同的 Security
不可能既是共同基金又是股票。
你是对的,为了添加新的具体 Security
记录,基础 Securities
Table 都需要一行(必须先插入,因为它们是从 subclass tables 到 base table) 的 FK,然后在 subclass tables 之一中插入一行,与其余 'specific' 数据。
如果在 Stock
和 Mutual Fund
之间添加外键,则无法将新行插入 table。
完整的模式通常是这样的:
CREATE TABLE BaseTable
(
Id INT PRIMARY KEY, -- Can also be Identity
... Common columns here
Discriminator, -- Type usually has a small range, so `INT` or `CHAR` are common
);
CREATE TABLE SubClassTable
(
Id INT PRIMARY KEY, -- Not identity, must be manually inserted
-- Specialized SubClass columns here
FOREIGN KEY (Id) REFERENCES BaseTable(Id)
);
我正在学习 pluralsight 课程,该课程目前正在使用 entity framework 代码优先方法构建 MVC 应用程序。我对项目使用的数据库架构感到困惑。
如您所见,Securities 与其相关的 tables 之间的关系似乎是一对一的,但是当我意识到没有外键来关联这两个子项时,混乱就来了- tables 并且它们似乎共享相同的主键列。
之前的视频对证券模型 class 进行了抽象,以便 "Stock" 和 "MutualFund" 模型 class 继承它并包含所有相关数据。然而,对我来说,似乎可以使用几个外键来完成同样的事情。
我想我的问题是这种链接 table 的方法在 SQL 或 EF 中是否有任何有用的用途?在我看来,为了为一个 table 创建一个新记录,所有 table 都需要一个新记录,这是我真正感到困惑的地方。
在 ORM 和 EF 术语中,此设置称为 "Table per Type" 继承范例,其中每个子table class,一个基础 class table,子class和基class共享主键。
例如在这种情况下,Securities_Stock
和 Securities_MutualFund
是 Securities
基础 class / table 的两个子 class(可能是抽象的)。
关系将是 0..1 (subclass) to 1 (base class)
- 即每个 table Securities
行仅存在 Securities_MutualFund
或 Securities_Stock
中的记录之一。
基数 table 上也经常有一个鉴别器列来指示子class table 到 join
到哪个,但这似乎不是这里的案例。
使用外键在子 class 与基 table 之间强制执行引用完整性也很常见。
回答你的问题,之所以两个subclass instance
table之间没有FK是因为每个instance
(有唯一的Id)只会出现在子 class table 之一中 - 相同的 Security
不可能既是共同基金又是股票。
你是对的,为了添加新的具体 Security
记录,基础 Securities
Table 都需要一行(必须先插入,因为它们是从 subclass tables 到 base table) 的 FK,然后在 subclass tables 之一中插入一行,与其余 'specific' 数据。
如果在 Stock
和 Mutual Fund
之间添加外键,则无法将新行插入 table。
完整的模式通常是这样的:
CREATE TABLE BaseTable
(
Id INT PRIMARY KEY, -- Can also be Identity
... Common columns here
Discriminator, -- Type usually has a small range, so `INT` or `CHAR` are common
);
CREATE TABLE SubClassTable
(
Id INT PRIMARY KEY, -- Not identity, must be manually inserted
-- Specialized SubClass columns here
FOREIGN KEY (Id) REFERENCES BaseTable(Id)
);