我有一个父InspectionData模型,该模型具有指向其他两个表(“组件”和“检查”)的复合主键和一个子WrittenFindings模型:
public class InspectionData
{
public int InspectionId { get; set; }
public virtual Inspection Inspection { get; set; }
public int? ComponentId { get; set; }
public virtual Component Component { get; set; }
public virtual WrittenFinding WrittenFinding { get; set; }
}
public class WrittenFinding
{
public int Id { get; set; }
public int? InspectionId { get; set; }
public int? ComponentId { get; set; }
public virtual InspectionData InspectionData { get; set; }
[Required]
public string Text { get; set; }
}
WrittenFinding是通过FluentApi在此处配置的:
modelBuilder.Entity<WrittenFinding>()
.HasOne(wf => wf.InspectionData)
.WithOne(id => id.WrittenFinding)
.HasForeignKey<WrittenFinding>(wf => new { wf.InspectionId, wf.ComponentId })
.OnDelete(DeleteBehavior.Cascade);
我正在尝试通过以下方式将它们添加到数据库中:
_context.InspectionData.Add(inspectionData);
await _context.SaveChangesAsync();
但是我这样做时遇到了外键约束:
SqlException: The INSERT statement conflicted with the FOREIGN KEY constraint "FK_WrittenFinding_InspectionData_InspectionId_ComponentId". The conflict occurred in database "InstantBSIContext-26452145-dc4a-4073-ae99-96b88874434d", table "dbo.InspectionData".
这就是我要添加的数据的样子:
InspectionId: 3
ComponentId: 1
WrittenFinding[InspectionId]: 3
WrittenFinding[ComponentId]: 1
WrittenFinding[Text]: <p><br></p>
我知道数据库中有一个ID为1的组件和一个ID为3的检查,并且我知道由于调试,我正确地发送和接收数据。
如果我从发送的数据中删除了WrittenFinding,那么InspectionData将被插入。
为什么我在使用复合外键的有效值时遇到此错误?