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?