2016-12-10 109 views
1

我想插入數據的三個關係表,但我不能這樣做:/C#實體框架插入關係表?

這裏是代碼

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(); 

我可以插入數據表的用戶,但電子郵件和電話,表不能插入數據?

這裏我表enter image description here

I changed my database like this

+0

表之間的關係如何?一對一? – Eldeniz

+0

我使用一對多 – oEs

+0

您是否在您的實體模型中創建關係? – Eldeniz

回答

1

在這種情況下,你會放棄這個錯誤

INSERT語句衝突與外鍵約束 「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(); 
+0

我像你說的,但仍然沒有工作 – oEs

+0

@ oEs請複製你的堆棧跟蹤和內部異常在這裏 –

0

我改變了我的數據庫這樣的 enter image description here

+0

這是你的答案? – Eldeniz

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();