Enttiy Framework中每个层次结构的表和每个混凝土类型的表?

时间:2016-03-30 07:42:43

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

我有以下POCO模型类:

//Not mapped to table, has all fields apart from foreign key
public abstract class FirstBaseModel {}

//Mapped to a table, has foreign key (eg. customerId)
public class Derived1Model : FirstBaseModel {}

//Mapped to a different table, has foreign key (eg. companyId)
public class Derived2Model : FirstBaseModel {}

//Mapped to the same table as Derived2Model
public class Derived3Model : Derived2Model {}

在上面的场景中,我会混合使用Table-per-Type和Table-per -ierarchy继承吗?

1 个答案:

答案 0 :(得分:0)

TPH是标准方案中的默认值 如果您需要TPT,您只需指定表名。

在你的情况下(我还添加了一些属性)

//Not mapped to table, has all fields apart from foreign key
public abstract class FirstBaseModel
{
    public int Id { get; set; }
}

//Mapped to a table, has foreign key (eg. customerId)
[Table("MyTable")]
public class Derived1Model : FirstBaseModel
{
    public string D1 { get; set; }
}

//Mapped to a different table, has foreign key (eg. companyId)
[Table("MyDifferentTable")]
public class Derived2Model : FirstBaseModel
{
    public string D2 { get; set; }
}

//Mapped to the same table as Derived2Model
[Table("MyDifferentTable")]
public class Derived3Model : Derived2Model
{
    public string D3 { get; set; }
}

这是EF在数据库上运行的查询

ExecuteNonQuery==========
CREATE TABLE [MyTable] (
 [Id] int not null identity(1,1)
, [D1] text null
);
ALTER TABLE [MyTable] ADD CONSTRAINT [PK_MyTable_b9ce81de] PRIMARY KEY ([Id])
ExecuteNonQuery==========
CREATE TABLE [MyDifferentTable] (
 [Id] int not null identity(1,1)
, [D2] text null
, [D3] text null
, [Discriminator] varchar(128) not null
);
ALTER TABLE [MyDifferentTable] ADD CONSTRAINT [PK_MyDifferentTable_b9ce81de] PRIMARY KEY ([Id])