![](/img/trans.png)
[英]How to insert data for one to many relationship between two tables in WPF c# using Entity Framework?
[英]C# Entity Framework insert relationship tables?
我想插入數據三個關系表,但是我不能這樣做:/
這是代碼
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();
我可以插入數據用戶表,但電子郵件和電話表不能插入數據?
在這種情況下,您將收到此錯誤
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();
您可以使用
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();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.