【问题标题】:Code First: TPT inheritance - Specify a different name for the primary key column in each table代码优先:TPT 继承 - 为每个表中的主键列指定不同的名称
【发布时间】:2014-03-15 06:52:48
【问题描述】:

我已在 codeplex http://entityframework.codeplex.com/workitem/2087 上发布了我的问题。
这里也发布了一些问题,但没有成功回答。

Mapping TPT in EF Code First 4.1 w/ Different Primary Keys

Entity Framework 4 - TPT Inheritance in Features CTP5 (code first): rename foreign key column on inherited table

How can I use TPT inheritance models when primary keys have different names?

现在可以在使用 TPT 时为主键设置不同的列名吗? 可能与 6.1.0 一起使用

【问题讨论】:

    标签: 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
        
        }
        

        【讨论】:

          猜你喜欢
          • 2011-06-28
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-06-04
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多