如何使用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