[英]SQL - Can I have a column referencing one of many tables?
I want to use a single table to store contact information of various entities.我想使用一个表来存储各种实体的联系信息。
Contacts table example:联系人表示例:
The OwnerId should reference EITHER Users (ID) or Students (ID) as drawn below: OwnerId 应参考如下所示的用户 (ID) 或学生 (ID):
Is it possible to create multiple foreign key constraints on the OwnerId column?是否可以在 OwnerId 列上创建多个外键约束? I am using EF Core and would like to do include the contact information of each entity, instead of creating a separate query to get the Contacts, something like:
我正在使用 EF Core,并且希望包含每个实体的联系信息,而不是创建单独的查询来获取联系人,例如:
int userId = 1;
var users = _databaseContext.Users.Include(x => x.Contacts).Where(x => x.Id == userId).FirstOrDefault();
// same with Students
instead of:代替:
int userId = 1;
var user = _databaseContext.Users.Where(x => x.Id == userId).FirstOrDefault();
var userContacts = _databaseContacts.Contacts.Where(x => x.OwnerId == userId).ToList();
user.Contacts = userContacts;
// same with Students
So:所以:
You could do this sort of thing.你可以做这种事情。
CREATE TABLE ContactType (
ContactType varchar(8) NOT NULL,
CONSTRAINT ContactType_PK PRIMARY KEY CLUSTERED (ContactType)
)
INSERT INTO ContactType (ContactType)
VALUES
('Student'),
('Teacher')
CREATE TABLE Contact (
ContactId uniqueidentifier NOT NULL DEFAULT(NEWSEQUENTIALID()),
ContactType varchar(8) NOT NULL,
CONSTRAINT Contact_PK PRIMARY KEY CLUSTERED (ContactId),
CONSTRAINT User_UQ UNIQUE (ContactId, ContactType), -- To allow FK that enforces type from Student, Teacher, etc. tables.
CONSTRAINT Contact_FK_ContactType FOREIGN KEY (ContactType) REFERENCES ContactType (ContactType)
)
CREATE TABLE [User] (
ContactId uniqueidentifier NOT NULL,
Username varchar(32) NOT NULL,
CONSTRAINT User_PK PRIMARY KEY CLUSTERED (ContactId),
CONSTRAINT User_UQ_Username UNIQUE (Username),
CONSTRAINT User_FK_Contact FOREIGN KEY (ContactId) REFERENCES Contact (ContactId)
)
CREATE TABLE Student (
ContactId uniqueidentifier NOT NULL,
ContactType AS CAST('Student' AS varchar(8)),
CONSTRAINT Student_PK PRIMARY KEY CLUSTERED (ContactId),
CONSTRAINT Student_FK_Contact FOREIGN KEY (ContactId, ContactType) REFERENCES Contact (ContactId, ContactType)
)
CREATE TABLE Teacher (
ContactId uniqueidentifier NOT NULL,
ContactType AS CAST('Teacher' AS varchar(8)),
CONSTRAINT Teacher_PK PRIMARY KEY CLUSTERED (ContactId),
CONSTRAINT Teacher_FK_Contact FOREIGN KEY (ContactId, ContactType) REFERENCES Contact (ContactId, ContactType)
)
The answer came to me in a dream: https://entityframework.net/joining答案在梦中出现: https ://entityframework.net/joining
Use EF JOIN to get each entity's contacts based on the OwnerId and the Primary Key of said entity.使用 EF JOIN 根据 OwnerId 和所述实体的主键获取每个实体的联系人。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.