c# - Entity Framework 6 表名作为 FK 值

标签 c# entity-framework entity-framework-6 tablename user-defined-fields

我有以下两个数据库表。 “属性”表的目的是让用户能够在运行时为现有表引入更多字段。因此,所有表的所有用户定义属性都将存储在一个“属性”表中。数据库没有物理约束。我的问题是如何在 Entity Framework 6 中建立这两个表之间的关联?

enter image description here

enter image description here

最佳答案

重新设计您的数据库,以拥有一个在用户定义的属性持有者(例如学校)和属性本身之间链接的表:

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 会将其公开为每个 School 实体(或通过 AttributeOwnersAttributes 具有 FK 关系的任何其他实体)上的 Attributes 集合。

有一个小设计错误,如果您有两个表 SchoolsColleges,它们都链接到 AttributeOwners 那么它们都可以指向相同的 AttributeOwners.Id 值,以便它们共享用户定义的属性值。您可以通过使用检查其他表(通过 UDF)的 CHECK CONSTRAINT 来缓解这种情况,但是只要将新表添加到您的设计中,就需要更新它。

关于c# - Entity Framework 6 表名作为 FK 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33044818/

相关文章:

c# - VS 2008 中的 "Unable to start debugging"消息

c# - OOP:理解抽象

c# - Entity Framework - 如何使用自定义 DbContext 实现存储库?

entity-framework - Entity Framework T4 : POCOs implement generic interface?

c# - 使用C#4.0运行Python脚本报错non-ascii char

c# - 从属性创建枚举

c# - 无法加载 Entity Framework 提供程序类型?

entity-framework - 有没有人有一个非常完整的 EF 6.1 示例通用存储库?

.net - Oracle ODP.Net 与 Entity Framework 6 - 找不到 Entity Framework 数据库兼容提供程序

entity-framework - Entity Framework 4.3迁移可移动现有数据