Entity Framework Table 每个层次结构插入多个 ID 列

Entity Framework Table Per Hierarchy Inserting Multiple Id Columns

我认真地花了两个工作日尝试将 TPH 设置从数据库优先到代码优先。我得到的错误是 "Invalid Column Name Entity_EntityId/ Entity_Entity_Id1"

我已经草拟了一个非常基本的问题重现,如下所示:

      internal class Program
      {
        private static void Main(string[] args)
        {
          using (var context = new Context())
          {
            var baseClass = new Base {Name = "Test"};
            context.BaseClasses.Add(baseClass);
            context.SaveChanges();
            var baseClasses = context.BaseClasses.ToList();
          }
        }
      }

上下文:

      public class Context : DbContext
      {
        public Context() : base("TPH")
        {
        }

        public DbSet<Base> BaseClasses { get; set; }
        public DbSet<Derived> DervDerivedClasses { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
        }
      }

映射:

      public class BaseMap : EntityTypeConfiguration<Base>
      {
        public BaseMap()
        {
          HasKey(b => b.Id);

          Property(b => b.Name);
          HasOptional(b => b.AnotherClass)
            .WithMany(b => b.Bases)
            .HasForeignKey(b => b.AnotherClassId);

          Map(b => b.Requires("Disc").HasValue(1));
        }
      }

      public class DerivedMap : EntityTypeConfiguration<Derived>
      {
        public DerivedMap()
        {
          HasKey(b => b.Id);

          Property(b => b.Name);
          HasOptional(b => b.AnotherClass)
            .WithMany(b => b.Deriveds)
            .HasForeignKey(b => b.AnotherClassId);

          Map(b => b.Requires("Disc").HasValue(2));
        }
      }

      public class SecondDerivedMap : EntityTypeConfiguration<SecondDerived>
      {
        public SecondDerivedMap()
        {
          HasKey(b => b.Id);

          Property(b => b.Name);

          HasOptional(b => b.AnotherClass)
            .WithMany(b => b.SecondDeriveds)
            .HasForeignKey(b => b.AnotherClassId);

          Map(b => b.Requires("Disc").HasValue(3));
        }
      }

实体:

      public class Base
      {
        public int Id { get; set; }
        public string Name { get; set; }
        public int? AnotherClassId { get; set; }
        public AnotherClass AnotherClass { get; set; }
      }

      public class Derived : Base
      {
      }

      public class SecondDerived : Base
      {
      }

      public class AnotherClass
      {
        public int Id { get; set; }
        public ICollection<Base> Bases { get; set; }
        public ICollection<Derived> Deriveds { get; set; }
        public ICollection<SecondDerived> SecondDeriveds { get; set; }
      }

如何让 table 只有一个 "AnotherClassId?"

每个实体每个关系只应该有一个导航 属性 -- 你有三个(BasesDerivedsSecondDeriveds) . EF 看到这些属性并认为 AnotherClassBase 层次结构中的各种 类 之间存在三种不同的一对多关联。

如果您想从 AnotherClass 获取相关 Derived 实体的集合,您应该使用类似 anotherClassEntity.Bases.OfType<Derived>().

的东西