【发布时间】:2016-10-17 08:13:34
【问题描述】:
通过在 Entity Framework codefirst 中使用 Table per Type (TPT) 继承,我们可以像这样创建外键:
public abstract class Person
{
public int id { get; set; }
public string Name { get; set; }
public string Family { get; set; }
}
[Table("Doctors")]
public class Doctor : Person
{
public string ExpertTitle { get; set; }
}
[Table("Notes")]
public class Note : Doctor
{
public string Content { get; set; }
}
在上面的代码中,除了创建Doctors 表并将其与Persons 表关联之外,我们还可以创建Note 表并在Doctors 表和那个之间创建一对多的关系。
但是该标准是使用继承而不是使用如下所示的虚拟属性来创建所有外键吗?!
public class Doctor : Per
{
public string ExpertTitle { get; set; }
public virtual ICollection<Note> Notes { get; set; }
}
public class Note : Doctor
{
public string Content { get; set; }
public virtual Doctor Doctor { get; set; }
}
【问题讨论】:
-
从
Doctor派生Note有意义吗?我会在逻辑上独立于 ORM 对您的类进行建模。您不会仅将继承用于创建关系。 -
是的,你是对的......它只是一个示例代码......我的主要问题是:使用继承而不是使用虚拟属性创建所有外键是真的吗?
-
不,你绝对不想这样做。此外,您只能通过这种方式创建 1-2-1 关系。
-
感谢您的评论。
标签: entity-framework ef-code-first entity-framework-6 code-first table-per-type