2016-12-10 202 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();