首页 文章

代码优先:TPT继承 - 为每个表中的主键列指定不同的名称

提问于
浏览

2 回答

  • 0

    在TPT中,你're essentially do not want to declare the key in the subclasses, you'否则会错过这一点 .
    如果必须具有不同的Id名称,只需在子类中将代理属性映射到基本Id .

    public class BaseEntity
    {
      public int Id { get; set; }    
    }
    
    public abstract class SubEntity : BaseEntity
    {
      public BaseId
      {
        get => Id;
        set => Id = value;
      }
    }
    

    考虑将子字段标记为NotMapped,以防您不应将它们包含在LINQ查询中 .

  • -1

    看看这段代码片段 . 它的工作正确我:

    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(使用流畅的API):

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Employee>()
            .Property(e => e.ID)
            .HasColumnName("EmployeeID");
    }
    

相关问题