简体   繁体   中英

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?

在此处输入图片说明

在此处输入图片说明

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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