繁体   English   中英

SQL - 我可以有一个引用多个表之一的列吗?

[英]SQL - Can I have a column referencing one of many tables?

我想使用一个表来存储各种实体的联系信息。

联系人表示例:

在此处输入图像描述

OwnerId 应参考如下所示的用户 (ID) 或学生 (ID):

在此处输入图像描述

是否可以在 OwnerId 列上创建多个外键约束? 我正在使用 EF Core,并且希望包含每个实体的联系信息,而不是创建单独的查询来获取联系人,例如:

int userId = 1;

var users = _databaseContext.Users.Include(x => x.Contacts).Where(x => x.Id == userId).FirstOrDefault();
// same with Students

代替:

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

所以:

  • 每个人都是联系人。
  • 有些联系人是用户,有些不是。
  • 有些联系人是学生,有些不是。
  • 有些联系人是老师,有些不是。

你可以做这种事情。

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

答案在梦中出现: https ://entityframework.net/joining

使用 EF JOIN 根据 OwnerId 和所述实体的主键获取每个实体的联系人。

暂无
暂无

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

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