使用linq将数据保存到数据库

问题描述:

我的代码将数据保存到数据库时遇到问题。我有一个文本框和一个组合框,但是当我在文本框中键入数据并在组合框中选择数据并单击保存时,没有任何反应,并且在编译期间没有发现错误。我能否知道究竟出了什么问题,并给我一些解决办法?使用linq将数据保存到数据库

enter code here private void btnCreate_Click(object sender, EventArgs e) 
    { 
     using (testEntities Setupctx = new testEntities()) 
     { 
      string selectST = cbSeats.SelectedItem.ToString(); 
      string inputST = txtStation.Text; 

      var createStation = (from createST in Setupctx.stations 
            where createST.Seats == selectST 
            where createST.Station1 == inputST 
            select createST).SingleOrDefault(); 
      if (createStation != null) 
      { 
       Setupctx.stations.AddObject(createStation); 
       Setupctx.SaveChanges(); 
       txtStation.Text = ""; 

       MessageBox.Show("New Station Has Been Created."); 
      } 
     } 
    } 

您的帮助将不胜感激。

+0

您试图更新“createStation”或创建一个新工作站吗? – 2012-07-13 03:35:19

这是做它的正确方法。

private void btnCreate_Click(object sender, EventArgs e) 
    { 
     using (testEntities Setupctx = new testEntities()) 
     { 
      string[] stations = StationNameList(); 
      station creStation = new station(); 
      creStation.Station1 = txtStation.Text; 
      creStation.Seats = cbSeats.SelectedItem.ToString(); 
      if (stations.Contains(txtStation.Text)) 
      { 
       MessageBox.Show("This Station is already been created. Please enter a new Station."); 
      } 
      else 
      { 
       Setupctx.stations.AddObject(creStation); 
       Setupctx.SaveChanges(); 
       txtStation.Text = ""; 
       cbSeats.SelectedIndex = -1; 
       MessageBox.Show("New Station Has Been Created."); 
      } 
     } 
    } 

只是为了检查出榜单:

  • 是否已进行了确认按钮事件处理程序挂钩?

当你说

什么也没有发生

你的意思是事件处理函数不是叫什么名字?你实际上没有对从数据库中检索到的电台做任何事情。您将它重新添加到您已从中拉出的电台列表中。

+0

含义我的select语句是错误的?我该怎么做,因为我想通过在文本框中键入文本并从组合框中选择值来添加到我的数据库中。任何解决方案 – Philemon 2012-07-13 03:23:07

+0

如果您可以通过代码中的某些内嵌注释来澄清代码应该做什么 – JamesD 2012-07-13 04:47:23

我同意@JamesD确保调用事件处理函数。

此外,当您从linq查询中获取对象并对其进行更改时,您需要通过在DataContext上调用SubmitChanges()来保存这些更改。 (我假设Setupctx是一个DataContext对象)。

这里阅读有关SubmitChanges()

另外,如果您使用的是SQL或没有,我不知道。如果是这样,这里是一个伟大的教程:Linq to SQL Tutorial

你需要创建一个新的电台对象是这样的:

if (createStation != null) 
    { 
    var obj = new Staion(); 
    obj.Seats=selectST; 
    obj.Staion1=inputST; 


    Setupctx.Staions.Add(obj); 
    Setupctx.SubmitChanges(); 

    txtStation.Text = ""; 

    MessageBox.Show("New Station Has Been Created."); 
} 

更多关于LINQ To SQL here