如何使用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();
它在哪裏拋出此錯誤? 「似乎在停止之後停止」是什麼意思? – Enigmativity
爲comboBox4.SelectedItem.ToString()在linq query4之外創建一個字符串變量,並用該變量替換。 var value = comboBox4.SelectedItem.ToString(); var query4 =(從ctx.hospitals中的h where h.name == value select h.hospId).FirstOrDefault(); – KrishnaDhungana