Primary Key Violation: Inheritance using EF Code First

后端 未结 3 572
时光取名叫无心
时光取名叫无心 2021-01-15 08:35

I have following EF code first code. I am getting the following exception:

\'GiftCouponPayment\' does not contain an identity column.

<
3条回答
  •  走了就别回头了
    2021-01-15 08:54

    You are not specifying the ID field for your TPC / TPT mappings. Even with inheritance you need to do this when not running a TPH mappings. (To note, I'm also not sure on the MapInheritedProperties() call... This is generally used for TPH... not TPT)

     //Fluent API - Table per Concrete Type (TPC)
     modelbuilder.Entity()
          .HasKey(x => x.PaymentComponentID)
          .Map(m =>
          {
              m.MapInheritedProperties();
              m.ToTable("GiftCouponPayment");
          })
          .Property(x => x.PaymentComponentID)
          .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
    

    This needs to be on each and every class mapping from the concrete type. If it were me I would go with TPH mapping where GiftCoupon as well as the other inheritance mapping so you end up with 1 table to represent the entire tree of objects using a discriminator column.

    Regardless... The other thing you are missing in your base class is:

    public byte[] Version { get; set; }
    

    And the associated mapping for:

    Property(x => x.Version).IsConcurrencyToken()
    

    Which allows for optimistic concurrency.

    Hopefully this helps a bit, let me know if you need further assistance or clarification.

提交回复
热议问题