1

I have the following defined in a TPH schema:

public abstract class Payment {
        [Key]
        [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
        public int PaymentId { get; set; }

        public DateTime DateOfPayment { get; set; }
        public double Amount { get; set;}
    }

public class PeerPayment : Payment {

    public PeerPayment() { }

    [ForeignKey("FromUser")]
    public User FromUser { get; set; }
    public int FromUserId { get; set; }

    [ForeignKey("ToUser")]
    public int ToUserId { get; set; }
    public virtual User ToUser { get; set; }

}

public class FeaturePayment : Payment {

    [ForeignKey("FromUser")]
    public User FromUser { get; set; }
    public int FromUserId { get; set; }

    public virtual Feature Feature { get; set; }

    public string StripeTokenId { get; set; }
    public string EmailAddress { get; set; }

}

Then, my entity relations are as follows:

public class FeaturePaymentConfiguration : EntityTypeConfiguration<FeaturePayment> {
    public FeaturePaymentConfiguration() {
        HasRequired(s => s.Feature).WithOptional(s => s.FeaturePayment);
    }
}

public class PeerPaymentConfiguration : EntityTypeConfiguration<PeerPayment> {
    public PeerPaymentConfiguration() {
        // One-to-Many
        HasOptional(s => s.Review).WithMany().HasForeignKey(s => s.ReviewId);
    }
}

The idea is that Payments can be one of two types, but that only one type has FK constraints against Feature. When I do the following:

            var payment = new PeerPayment() {
                FromUserId = user1.UserId,
                ToUserId = user2.UserId,
                DateOfPayment = DateTime.UtcNow
            };
            db.Payments.Add(payment);
            db.SaveChanges(); 

I get an error:

The INSERT statement conflicted with the FOREIGN KEY constraint "FK_dbo.Payment_dbo.Feature_PaymentId"

Is TPH inheritance incompatible with type-specific FK constraints?

RobVious
  • 12,685
  • 25
  • 99
  • 181
  • Pretty sure you can't have a derived class with a required FK relationship. If you look at the generated table, the FK ID needs to be filled in regardless of what type you choose. Also, perhaps `FromUser` should be in your base class here. – DavidG Aug 17 '16 at 23:02
  • @DavidG - thanks for this. Is the solution to go TPT, or bloat my business logic to enforce the FK only on one type? And - I attempted to push `FromUser` up, but I get the following: `The foreign key component 'FromUserId' is not a declared property on type 'FeaturePayment'. Verify that it has not been explicitly excluded from the model and that it is a valid primitive property.` – RobVious Aug 17 '16 at 23:07
  • I'm still facing this issue. is there any other ways to overcome this issue – LordDraagon Nov 29 '19 at 14:21

0 Answers0