每个层次结构插入多个Id列的实体框架表

时间:2015-08-14 21:21:53

标签: entity-framework ef-code-first entity-framework-6 code-first table-per-hierarchy

我认真地花了两个工作日尝试从Database First到Code的TPH设置。我得到的错误是“无效的列名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; }
      }

如何让表格只有一个“AnotherClassId?”

0 个答案:

没有答案