[英]Entity Framework: how to map multiple tables with different keys to one entity?
我有這樣的數據庫結構:
create table Person (
ID bigint identity not null,
FirstName varchar(100),
LastName varchar(100),
-- etc... lot's of generic fields that apply to a person, e.g. phone, address
)
create table Teacher (
ID bigint identity not null,
PersonID bigint not null,
EmploymentDate date,
-- plus a bunch of other teacher-specific fields
)
create table Student (
ID bigint identity not null,
PersonID bigint not null,
EnrollmentDate date,
-- plus a bunch of student-specific fields
)
create table SystemUser (
ID bigint identity not null,
PersonID bigint not null,
UserName varchar(50) not null,
-- plus any user specific fields
)
Person
與所有其他字段之間的關系是1-> 0:1,並且Person
每個“子類”在PersonID
上都有一個唯一的鍵。 一個SystemUser
可能是同一人擔任Teacher
或Student
; 實際上,可以想象您擁有一個全部都是三個人的人。
現在,我要使EF實體代表Teacher
, Student
和SystemUser
,每個實體實際上都繼承自Person
(一等獎),或者至少在類中包含Person
字段,隱式映射到兩個基礎表。
我在網上發現了很多示例,這些示例共享相同的主鍵,但是沒有共享相同的主鍵的PersonID
,即派生表上的PersonID
映射到Person
表上的ID
。
你如何做到的?
實際上,可以想象您擁有一個全部都是三個人的人。
如果這是您的要求,則不得將人員與其他班級一起映射。 您仍必須具有單獨的Person
類和單獨的PersonDetail
類,其中PersonDetail
可以派生通過TPT繼承映射的Student
, Teacher
和SystemUser
類。 您必須將Person
和PersonDetail
之間的關系PersonDetail
為一對多,以支持該要求。
一個具有繼承關系的映射人將具有此屬性
Person
會成為Student
, Teacher
或SystemUser
Person
的記錄無法改變-這意味着Student
將永遠是Student
,它是不能改變的,例如,以Teacher
而不先刪除Person/Student
,並創造新的Person/Teacher
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.