实体框架6表名为FK值

时间:2015-10-09 18:20:09

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

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

enter image description here

enter image description here

1 个答案:

答案 0 :(得分:2)

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

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

通过使用此设计,您现在可以为用户定义的字段提供数据库级参照完整性。实体框架将在每个School实体(或通过AttributesAttributeOwners建立FK关系的任何其他实体)上将其公开为Attributes集合。

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