简体   繁体   English

实体框架 6 表名作为 FK 值

[英]Entity Framework 6 tablename as FK value

I have following two DB tables.我有以下两个数据库表。 The purpose of "attributes" table is to provide user the ability to introduce more fields for existing tables at the runtime. “属性”表的目的是让用户能够在运行时为现有表引入更多字段。 So all user-defined attributes for all tables will be stored in one "attributes" table.因此,所有表的所有用户定义属性都将存储在一个“属性”表中。 There is no physical constraint on database.对数据库没有物理约束。 My question is how to make association between these two tables in Entity Framework 6?我的问题是如何在 Entity Framework 6 中建立这两个表之间的关联?

在此处输入图片说明

在此处输入图片说明

Re-design your database to have a table that links between user-defined attribute holders (eg schools) and the attributes themselves:重新设计您的数据库,以在用户定义的属性持有者(例如学校)和属性本身之间建立一个表:

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

By having this design you can now have database-level referential integrity for user-defined fields.通过这种设计,您现在可以拥有用户定义字段的数据库级参照完整性。 Entity Framework will expose this as an Attributes collection on each School entity (or any other entity that has an FK relationship with Attributes via AttributeOwners ).实体框架将其公开为每个 School 实体(或通过AttributeOwnersAttributes具有 FK 关系的任何其他实体)上的 Attributes 集合。

There is a small design bug in that if you have two tables Schools and Colleges which both link to AttributeOwners then they could both point to the same AttributeOwners.Id value so they would share user-defiend attribute values.有一个小的设计错误,如果您有两个表SchoolsColleges ,它们都链接到AttributeOwners那么它们都可以指向相同的AttributeOwners.Id值,因此它们将共享用户定义的属性值。 You can mitigate this by using a CHECK CONSTRAINT that checks other tables (by way of a UDF), however this will need to be updated whenever new tables are added to your design.您可以通过使用检查其他表(通过 UDF)的CHECK CONSTRAINT来缓解这种情况,但是只要将新表添加到您的设计中,就需要更新。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM