【问题标题】:Entity Framework Code First mapping situationEntity Framework Code First 映射情况
【发布时间】:2012-10-15 17:19:42
【问题描述】:

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

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

现有的应用是这样的:

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

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

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

如何使用 Code First 进行映射?

起初我考虑保留我的结构,我的意思是,Supplier 抽象类以及由此派生的个人和公司。因为我需要先在供应商表上插入实体(生成标识字段),所以个人和公司模型类似乎都将映射到供应商表。

但是它怎么可能接收抽象类并根据类型插入任一专业化表中呢?如果没有自定义 SQL,我认为这是不可能的,这让我认为我的方法是错误的。

提前感谢您的帮助。

【问题讨论】:

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


    【解决方案1】:

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

    【讨论】:

    • 这是我 100% 的情况。非常感谢!
    猜你喜欢
    • 1970-01-01
    • 2013-05-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多