2016-12-10 6 views
1

私はデータを3つの関係表を挿入したいが、私はこれを行うことはできません:/C#Entity Frameworkの挿入関係テーブル?

ここでは、コード

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

テーブル間のどのような関係を使用することができますか? 1対1? – Eldeniz

+0

私は多くを使用します – oEs

+0

エンティティモデルで関係を作成していますか? – Eldeniz

答えて

1

このエラー

にFOREIGN KEY制約 "FK_Emails_Users" と競合INSERT文を与えたことになります。競合はデータベース "****"、テーブル "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(); 
関連する問題