![](/img/trans.png)
[英]I have many tables and one main one, how can I take there column names from the main one?
[英]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.