Linq to Entity 在 db 中插入数据
本文关键字:插入 数据 db to Entity Linq | 更新日期: 2023-09-27 18:30:26
如何使用
Linq to Entity在BidingNavigator上单击"保存"后插入添加到GridView的数据。
我正在尝试将数据添加到数据库,但出现了一些问题。我使用以下代码显示数据:
。
private void PostojeciPRojekti_Load(object sender, EventArgs e)
{
dbcontext = new logicrms2Entities1();
var projekti = from c in dbcontext.projekti
select c;
projektiBindingSource.DataSource = projekti.ToList();
projektiGridControl.Refresh();
}
。
编辑
我尝试使用以下方法保存数据:
private void projektiBindingNavigatorSaveItem_Click(object sender, EventArgs e)
{
dbcontext.SaveChanges();
gridView1.RefreshData();
}
首先在表单中维护新添加对象的列表:
private List<projekti> addedList = new List<projekti>();
然后,在 DataGridView 上处理 RowsAdd 事件:
dataGridView1.RowsAdded += new DataGridViewRowsAddedEventHandler(dataGridView1_RowsAdded);
接下来,将任何添加的对象添加到 RowsAdd 事件处理程序中的列表中:
private void dataGridView1_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
{
addedList.Add(dataGridView1.Rows[e.RowIndex].DataBoundItem as projekti);
}
最后,在导航器的保存按钮单击事件处理程序方法中,您可以存储对象:
private void saveButton_Click(object sender, EventArgs e)
{
var dbcontext = new logicrms2Entities1();
addedList.ForEach(p=> dbcontext.projeckit.Add(p));
dbcontext.SaveChanges()
}