我有两个表,一对一的关系,我在项目表的ID中使projectDetails FK的DetailsID:

 projects:
         ID,         //has FK With DetailsID in Details table & auto identity (1,1)
         ProjectName,
         Areas,
         PaymentSystem,
         ReceivedDate,
         PropertyClassification,
         ProjectImage

  ProjectDetails:
     DetailsID ,auto identity ( 1,1)
     ProjectDetailName,
     ProjectDetailImage


我试图在项目表中插入新记录,这行代码给我这个错误:

    con.Open();
    comm.ExecuteNonQuery(); // when execute



  System.Data.SqlClient.SqlException:'INSERT语句与FOREIGN KEY约束“ FK_Projects_ProjectDetails”发生冲突。数据库“ AlamaarRealEstate”的表“ dbo.ProjectDetails”的列“ DetailsID”中发生了冲突。


这是我存储要插入的内容:

ALTER proc [Insert_Project]
   @Projectname                    NVARCHAR(MAX) ,
   @areas                          NVARCHAR(MAX) ,
   @Paymentsystem                  NVARCHAR(MAX) ,
   @Receiveddate                   date ,
   @Classification                 NVARCHAR(MAX) ,
   @Projectimage                   Nvarchar(MAX)
  as

  INSERT INTO dbo.Projects
      (
        ProjectName,
        Areas,
        PaymentSystem,
        ReceivedDate,
        PropertyClassification,
        ProjectImage
      )
 VALUES
      (
        @Projectname ,
        @areas,
        @Paymentsystem ,
        @Receiveddate ,
        @Classification,
        @Projectimage

      )

最佳答案

问题解释了答案。 Referential Integrity的维护不正确,您正在尝试将其主值不存在的子表插入。请先在Project_details中插入值。这样可以解决您的问题。如果没有引发错误,只需在插入前检查DetailID表中Projects的存在。

08-04 17:04