【问题标题】:Code First: TPT inheritance - Specify a different name for the primary key column in each table代码优先:TPT 继承 - 为每个表中的主键列指定不同的名称
【发布时间】:2014-03-15 06:52:48
【问题描述】:
【问题讨论】:
标签:
entity-framework
inheritance
ef-code-first
【解决方案1】:
在 TPT 中,您基本上不想在子类中声明键,否则您会错过重点。
如果您必须使用不同的 Id 名称,只需将子类中的代理属性映射到基 Id 一个即可。
public class BaseEntity
{
public int Id { get; set; }
}
public abstract class SubEntity : BaseEntity
{
public BaseId
{
get => Id;
set => Id = value;
}
}
考虑将子字段标记为NotMapped,以防您不应该将它们包含在您的 LINQ 查询中。
【解决方案2】:
看看这个代码片段。它的工作对我来说是正确的:
public partial class Person
{
// Any other PK name can thrown an exception
public int ID { get; set; }
}
public partial class Employee : Person
{
// Hide base class ID
private new int ID { get; set }
// Define derived class ID (that wrapped inherited ID)
[NotMapped]
public int EmployeeID
{
get { return base.PersonID; }
set { base.PersonID = value; }
}
}
现在,我们必须重命名数据库表的继承 ID(使用 fluent API):
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Employee>()
.Property(e => e.ID)
.HasColumnName("EmployeeID");
}
【解决方案3】:
在 EF 6.4 中,我能够使用 ColumnAttribute 重命名依赖类中的主键列
[Table("Person")]
public class Person
{
[Key]
public virtual int PersonId { get; set; }
// Person atributes...
}
[Table("Employee")]
public class Employee : Person
{
[Column("EmployeeId")] // <- Name of the primary Key column in the Database
public override int PersonId { get; set }
// Employee Attributes
}