使用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.");
}
}
}
您的帮助将不胜感激。
答
这是做它的正确方法。
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.");
}
}
}
答
我同意@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
您试图更新“createStation”或创建一个新工作站吗? – 2012-07-13 03:35:19