c# - Entity Framework : how to map multiple tables with different keys to one entity?

标签 c# entity-framework entity-framework-5

我有这样的数据库结构:

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 可能与 TeacherStudent 是同一个人;事实上,你可以想象得到一个同时具备这三者的人。

现在,我想让 EF 实体代表 TeacherStudentSystemUser,它们中的每一个实际上都继承自 Person(一等奖),或者至少在类中包含 Person 字段,隐式映射到两个基础表。

我在网上找到了很多示例,它们共享相同的主键,但没有一个示例不共享相同的主键,即派生表上的 PersonID 映射到 ID Person 表上。

你是怎么做到的?

最佳答案

in fact you could conceivably have a person who is all three.

如果这是您的要求,您不得将 person 与其他类映射在一起。您仍然必须有单独的 Person 类和单独的 PersonDetail 类,其中 PersonDetail 可以派生 StudentTeacher SystemUser 类映射到 TPT 继承。您必须将 PersonPersonDetail 之间的关系映射为一对多关系以支持该要求。

一个你映射具有继承关系的人你的模型将具有这个属性

  • 一个 Person 将是 StudentTeacherSystemUser
  • 如果您确实有一个扮演多个角色的真人,您将需要在数据库中为每个角色提供多个 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/

相关文章:

c# - 泛型和 Entity Framework

entity-framework - 使用 Entity Framework 的动态\用户可扩展实体

c# - 是否可以在调用 DbContext.SaveChanges 之前查询 Entity Framework ?

c# - 如何...显示数据库中的数据

c# - 等效于 DbContext 上的 ObjectContext.AddObject(entityName, entity)

c# - 在并发数据库更新时锁定 Entity Framework 代码

c# - 定制连载

c# - 如何在 LINQ 中随机使用 First()?

c# - c#中备注标签的用途是什么

c# - 我如何获得 XElement 的第一个 child ?