我被困在asp.net中的简单代码上
我想将简单的字符串值插入1个父表(帐户)和1个子表(Applicant_bio)。
现在,我可以将数据放入父表,但是当我尝试访问子表时,出现以下错误:
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";
}
这是数据库详细信息
enter image description here
最佳答案
发生错误是因为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";
}
关于c# - 使用Linq to sql在子表中插入数据(3层体系结构),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35297333/