2016-12-02 141 views
1

如何使用linq和c#插入記錄到數據庫?使用Linq插入新記錄

我的功能看起來是這樣的:

private void submitEntry(object sender, RoutedEventArgs e) { 
     using (var ctx = new ServiceDataContext()) { 
      try { 
       String selection1 = comboBox1.SelectedItem.ToString(); 
       String[] spl1 = selection1.Split(' '); 
       var cond1 = spl1[ 0 ]; 
       var cond2 = spl1[ 1 ]; 
       var query1 = (from p in ctx.products where p.brand == cond1 && p.model == cond2 select p.prodId).FirstOrDefault(); 

       String selection5 = comboBox5.SelectedItem.ToString(); 
       String[] spl5 = selection5.Split(',',' '); 
       var cond1_5 = spl5[ 0 ]; 
       var cond2_5 = spl5[ 2 ]; 
       var query5 = (from c in ctx.contactPersons where c.lastName == cond1_5 && c.firstName == cond2_5 select c.contId).FirstOrDefault(); 

       var query4 = (from h in ctx.hospitals where h.name == comboBox4.SelectedItem.ToString() select h.hospId).FirstOrDefault(); 

       mainWindow mainClass = new mainWindow(); 

       MessageBox.Show(mainClass.logId.ToString()); 

       entry ent = new entry { prodId = Convert.ToInt32(query1), 
             prodQty = Convert.ToInt32(textBox.Text), 
             hospId = Convert.ToInt32(query4), 
             contId = Convert.ToInt32(query5), 
             freqMaintenance = Convert.ToInt32(textBox1.Text), 
             empId = Convert.ToInt32(emp) 
             }; 
       ctx.entries.InsertOnSubmit(ent); 
       ctx.SubmitChanges(); 
      } catch { 
       MessageBox.Show("ERROR 404: Database Not Found"); 
      } 
     } 
    } 

它扔我這個異常:Exception thrown: 'System.Data.SqlClient.SqlException' in System.Data.Linq.dll

我試圖通過增加MessageBox.Show("1");來測試它,它似乎停止apearing後ctx.SubmitChanges();

+0

它在哪裏拋出此錯誤? 「似乎在停止之後停止」是什麼意思? – Enigmativity

+0

爲comboBox4.SelectedItem.ToString()在linq query4之外創建一個字符串變量,並用該變量替換。 var value = comboBox4.SelectedItem.ToString(); var query4 =(從ctx.hospitals中的h where h.name == value select h.hospId).FirstOrDefault(); – KrishnaDhungana

回答

0

我只是想知道爲什麼它對你有效

ctx。 條目 .InsertOnSubmit(ent);

當你的模型是進入

entry ent = new entry { prodId = Convert.ToInt32(query1), 
              prodQty = Convert.ToInt32(textBox.Text), 
              hospId = Convert.ToInt32(query4), 
              contId = Convert.ToInt32(query5), 
              freqMaintenance = Convert.ToInt32(textBox1.Text), 
              empId = Convert.ToInt32(emp) 
              }; 

,因爲我知道LINQ語法不處理複數。

其實

我期待像

ctx.entry.InsertOnSubmit(ent); 

否則張貼出你的DbContext代碼可能會有幫助。

0

這是一個SqlException,你必須調試sql語句,對於這個日誌sql

catch (SqlException ex) 
{ 
    SqlError err = ex.Errors[0]; 
    string message = string.Empty; 
    Console.WriteLine("Error: {0}", message); 
}