我想插入数据三个关系表,但我不能这样做:/
这是代码
hali_sahaEntities con = new hali_sahaEntities();
Users user = new Users();
Emails email = new Emails();
Phones phone = new Phones();
user.Name = textBox1.Text;
user.Surname = textBox7.Text;
user.IdentityNumber = Convert.ToInt32( textBox2.Text);
user.Adress = textBox5.Text;
user.Comment = textBox6.Text;
email.TCKN = Convert.ToInt32( textBox2.Text);
email.Email = textBox4.Text;
phone.TCKN = Convert.ToInt32(textBox2.Text);
phone.Phone = textBox3.Text;
con.Users.Add(user);
con.Emails.Add(email);
con.Phones.Add(phone);
con.SaveChanges();
我可以插入数据用户表,但电子邮件和电话表不能插入数据吗?
答案 0 :(得分:1)
在这种情况下,您将收到此错误
INSERT语句与FOREIGN KEY约束“FK_Emails_Users”冲突。冲突发生在数据库“****”,表“dbo.Users”,列“IdentityNumber”中。 声明已经终止。
所以你可以通过这个改变来修复它:
con.Users.Add(user);
con.SaveChanges();//*Because of the relationship*
con.Emails.Add(email);
con.Phones.Add(phone);
con.SaveChanges();
答案 1 :(得分:1)
您可以使用
hali_sahaEntities con = new hali_sahaEntities();
Users user = new Users();
user.Name = textBox1.Text;
user.Surname = textBox7.Text;
user.IdentityNumber = Convert.ToInt32( textBox2.Text);
user.Adress = textBox5.Text;
user.Comment = textBox6.Text;
Emails email = new Emails();
email.TCKN = Convert.ToInt32( textBox2.Text);
email.Email = textBox4.Text;
user.Emails.Add(email);//Emails is virtual proparty
Phones phone = new Phones();
phone.TCKN = Convert.ToInt32(textBox2.Text);
phone.Phone = textBox3.Text;
user.Phones.Add(phone);//Phones is virtual proparty
con.Users.Add(user);
con.SaveChanges();
答案 2 :(得分:0)