使用Linq插入新记录

时间:2016-12-02 03:00:54

标签: c# linq linq-to-sql

如何使用linq和c#?

将记录插入数据库

我的功能如下:

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");对其进行测试,似乎在ctx.SubmitChanges();

之后停止播放

2 个答案:

答案 0 :(得分:0)

这是一个SqlException,你必须调试sql语句,对于这个日志sql

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

答案 1 :(得分: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代码可能会有帮助。