Entity Framework 6 表名作为 FK 值
Entity Framework 6 tablename as FK value
我有以下两个数据库 table。 "attributes" table 的目的是为用户提供在运行时为现有 table 引入更多字段的能力。因此,所有 table 的所有用户定义属性都将存储在一个 "attributes" table 中。数据库没有物理限制。我的问题是如何在 Entity Framework 6?
中将这两个 table 关联起来
重新设计您的数据库,使 table 在用户定义的属性持有者(例如学校)和属性本身之间 link:
CREATE TABLE Schools (
Id bigint IDENTITY(1,1) PRIMARY KEY NOT NULL,
Name nvarchar(50) NOT NULL,
AttributeOwnerId bigint -- This column should have both a FOREIGN KEY constraint on AttributeOwners.Id and a UNIQUE constraint (so no two schools can share the same user-defined attributes)
)
CREATE TABLE AttributeOwners (
Id bigint IDENTITY(1,1) PRIMARY KEY NOT NULL
)
CREATE TABLE Attributes (
Id bigint IDENTITY(1,1) PRIMARY KEY NOT NULL
AttributeOwnerId bigint -- FOREIGN KEY constraint on AttributeOwners.Id
Name nvarchar(50),
Value nvarchar(50)
)
通过这种设计,您现在可以为用户定义的字段提供数据库级的引用完整性。 Entity Framework 会将此作为每个学校实体(或通过 AttributeOwners
与 Attributes
具有外键关系的任何其他实体)的属性集合公开。
有一个小的设计错误,如果你有两个 tables Schools
和 Colleges
,它们都是 link 到 AttributeOwners
那么他们可以两者都指向相同的 AttributeOwners.Id
值,因此它们将共享 user-defiend 属性值。您可以通过使用检查其他 table 的 CHECK CONSTRAINT
(通过 UDF)来缓解这种情况,但是只要将新的 table 添加到您的设计中,就需要更新它。
我有以下两个数据库 table。 "attributes" table 的目的是为用户提供在运行时为现有 table 引入更多字段的能力。因此,所有 table 的所有用户定义属性都将存储在一个 "attributes" table 中。数据库没有物理限制。我的问题是如何在 Entity Framework 6?
中将这两个 table 关联起来重新设计您的数据库,使 table 在用户定义的属性持有者(例如学校)和属性本身之间 link:
CREATE TABLE Schools (
Id bigint IDENTITY(1,1) PRIMARY KEY NOT NULL,
Name nvarchar(50) NOT NULL,
AttributeOwnerId bigint -- This column should have both a FOREIGN KEY constraint on AttributeOwners.Id and a UNIQUE constraint (so no two schools can share the same user-defined attributes)
)
CREATE TABLE AttributeOwners (
Id bigint IDENTITY(1,1) PRIMARY KEY NOT NULL
)
CREATE TABLE Attributes (
Id bigint IDENTITY(1,1) PRIMARY KEY NOT NULL
AttributeOwnerId bigint -- FOREIGN KEY constraint on AttributeOwners.Id
Name nvarchar(50),
Value nvarchar(50)
)
通过这种设计,您现在可以为用户定义的字段提供数据库级的引用完整性。 Entity Framework 会将此作为每个学校实体(或通过 AttributeOwners
与 Attributes
具有外键关系的任何其他实体)的属性集合公开。
有一个小的设计错误,如果你有两个 tables Schools
和 Colleges
,它们都是 link 到 AttributeOwners
那么他们可以两者都指向相同的 AttributeOwners.Id
值,因此它们将共享 user-defiend 属性值。您可以通过使用检查其他 table 的 CHECK CONSTRAINT
(通过 UDF)来缓解这种情况,但是只要将新的 table 添加到您的设计中,就需要更新它。