实体框架代码第一个映射情况

时间:2012-10-15 17:19:42

标签: c# entity-framework ef-code-first

我正在尝试使用EF 4.3 Code First将现有应用程序(使用纯ADO.Net)移植到新应用程序。值得一提的是,这是我第一次使用EF。

基本上我有一个供应商表,但有两个专业化表,其中的属性特定于两种类型的供应商。

以下是现有数据库的样子:

create table Supplier(
id_supplier int not null identity
--Bunch of other attributes
);

create table Individual(
id_individual int not null --not identity, gets the same value as the Supplier table
--Attributes specific to individuals
);

alter table Individual add constraint fk_individual_supplier
foreign key(id_individual) references Supplier(id_supplier);

create table Corporation(
id_corporation int not null --not identity, gets the same value as the Supplier table
--Attributes specific to corporations
);

alter table Corporation add constraint fk_corporation_supplier
foreign key(id_corporation) references Supplier(id_supplier);

因此,如表所示,供应商可以是个人或公司。

现有的应用程序是这样的:

  • 抽象类供应商及其属性
  • class来自供应商的个人及其附加属性
  • class Corporation派生自供应商及其附加属性

Ado.Net代码目前可以接收供应商对象,如果传递的对象属于公司类型,则传递的对象是个人类型或公司表时,会在单个表上生成记录。

因此,供应商的每条记录都将在个人或公司上有匹配的记录。此外,Individual和Corporation表没有数据库的任何其他表的外键。相反,这些关系都与Supplier表有关。生成ID的表格是供应商。

如何使用Code First映射?

起初我想保留我的结构,我的意思是,供应商抽象类和个人和公司从中衍生出来。因为我需要首先在Supplier表上插入Entity(生成标识字段),所以似乎Individual和Corporation模型类都将映射到Supplier表。

但它如何才能接收抽象类并根据类型插入任何一个特化表?我不认为没有自定义SQL会让我认为我的方法是错误的。

提前感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

这听起来像“每种类型的表”继承(TPT)。对于TPT,有一个基表,其中列对于所有派生类型是通用的,每个派生类型具有特定于类型的列。实体框架支持此模型。有关如何使用数据注释和流畅映射执行此操作的示例,请参阅this优秀博客文章。