我被困在 asp.net 的简单代码上我想将简单的字符串值插入到 1 个父表(帐户)和 1 个子表(Applicant_bio)。现在事情是这样的,我能够将数据放在父表中,但是当我尝试访问 Child 表时,它给了我以下错误:
The INSERT statement conflicted with the FOREIGN KEY constraint linq to sql
我已经明确设置了两个主键的值以匹配,因此没有冲突,因为表具有 1 到 1 的关系。这是我的代码:
public string Retreive_Applicants(Applicant_list user_details)
{
newDatabaseDataContext connection = new newDatabaseDataContext();
//Create a new instance of the applicant object
account account = new account();
account.account_id = 1;
account.account_type = "Applicant";
account.account_description = "";
account.account_title = user_details.account_title;
account.account_password = user_details.account_password;
connection.accounts.InsertOnSubmit(account);
connection.SubmitChanges();
account.applicant_bio= new applicant_bio();
account.applicant_bio.account_id = account.account_id; //Here's Where I have explicitly set the account id of applicant_bio to account_id of accounts table just created
account.applicant_bio.applicant_name = user_details.applicant_name;
account.applicant_bio.applicant_age = user_details.applicant_age;
account.applicant_bio.applicant_cnic = user_details.applicant_cnic;
connection.applicant_bios.InsertOnSubmit(account.applicant_bio);
connection.SubmitChanges(); //Here's where the error occurs
return "success";
}
这是数据库详细信息在此处输入图像描述
发生此错误是因为 linq 了解您尝试保存applicant_bio 还保存已经存在的新帐户对象,请尝试保存两者 它的工作方式如下:
public string Retreive_Applicants(Applicant_list user_details)
{
newDatabaseDataContext connection = new newDatabaseDataContext();
//Create a new instance of the applicant object
account account = new account();
account.account_id = 1;
account.account_type = "Applicant";
account.account_description = "";
account.account_title = user_details.account_title;
account.account_password = user_details.account_password;
account.applicant_bio= new applicant_bio();
//You dont need this line any more
//account.applicant_bio.account_id = account.account_id;
account.applicant_bio.applicant_name = user_details.applicant_name;
account.applicant_bio.applicant_age = user_details.applicant_age;
account.applicant_bio.applicant_cnic = user_details.applicant_cnic;
connection.accounts.InsertOnSubmit(account);
connection.SubmitChanges();
return "success";
}