我在 TPH 模式中定义了以下内容:
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; }
}
然后,我的实体关系如下:
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);
}
}
这个想法是Payments
可以是两种类型之一,但只有一种类型具有针对Feature
. 当我执行以下操作时:
var payment = new PeerPayment() {
FromUserId = user1.UserId,
ToUserId = user2.UserId,
DateOfPayment = DateTime.UtcNow
};
db.Payments.Add(payment);
db.SaveChanges();
我收到一个错误:
INSERT 语句与 FOREIGN KEY 约束“FK_dbo.Payment_dbo.Feature_PaymentId”冲突
TPH 继承与特定于类型的 FK 约束不兼容吗?