我在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
有FK约束。当我执行以下操作时:
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约束不兼容?