我有这样的数据库结构:
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
的每个“子类”在 上都有一个唯一的键>人号
。 SystemUser
可能与 Teacher
或 Student
是同一个人;事实上,你可以想象得到一个同时具备这三者的人。
现在,我想让 EF 实体代表 Teacher
、Student
和 SystemUser
,它们中的每一个实际上都继承自 Person
(一等奖),或者至少在类中包含 Person
字段,隐式映射到两个基础表。
我在网上找到了很多示例,它们共享相同的主键,但没有一个示例不共享相同的主键,即派生表上的 PersonID
映射到 ID
在 Person
表上。
你是怎么做到的?
最佳答案
in fact you could conceivably have a person who is all three.
如果这是您的要求,您不得将 person 与其他类映射在一起。您仍然必须有单独的 Person
类和单独的 PersonDetail
类,其中 PersonDetail
可以派生 Student
、Teacher
和 SystemUser
类映射到 TPT 继承。您必须将 Person
和 PersonDetail
之间的关系映射为一对多关系以支持该要求。
一个你映射具有继承关系的人你的模型将具有这个属性
- 一个
Person
将是Student
、Teacher
或SystemUser
- 如果您确实有一个扮演多个角色的真人,您将需要在数据库中为每个角色提供多个 Person 记录 - 每个都有其唯一的主键
- 现有
Person
记录的角色无法更改 - 这意味着Student
将始终是Student
并且无法更改为例如Teacher
而不是先删除Person/Student
并创建新的Person/Teacher
。
关于c# - Entity Framework : how to map multiple tables with different keys to one entity?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12998231/