使用实体框架和DBContext重新加载和更新
本文关键字:加载 更新 新加载 实体 框架 DBContext | 更新日期: 2023-09-27 18:27:59
好的,所以我尝试了一些东西,但一直被卡住。我曾经让更新按钮工作过,现在它不会更新了。删除按钮将工作并删除记录,但我无法在删除记录后刷新网格视图。我还希望在按下更新按钮并更新记录后重新加载gridview。这是我所拥有的:
protected void btnDelete_Click(object sender, EventArgs e)
{
switch (btnDelete.Text)
{
case DeleteButton:
try
{
if (txtLocationName.Text != null && txtSubAccountName.Text != null)
{
Location locationCheck = _context.Locations.ToList()
.First(x => x.Name == txtLocationName.Text && x.SubAccount == txtSubAccountName.Text);
if (locationCheck != null)
{
Location n = new Location
{
Id = grdvwLocationList.SelectedIndex,
Name = txtLocationName.Text,
SubAccount = txtSubAccountName.Text
};
_context.Locations.Remove(n);
_context.SaveChanges();
}
}
}
catch (Exception)
{
lblLocationNameNotification.Text = "Please type in a location/sub-account or select a location/sub-account that doesn't have a asset to delete.";
txtLocationName.Text = "";
txtSubAccountName.Text = "";
}
break;
case CancelButton:
Reload();
break;
}
}
public void PopulateLocationGridView()
{
var locations = _context.Locations.Where(l => l.CompanyId == CompanyId)
.OrderBy(l => l.Name)
.ToList();
grdvwLocationList.DataSource = locations;
grdvwLocationList.DataBind();
if (locations.Count > 0)
{
grdvwLocationList.SelectedIndex = 0;
RowSelected();
}
else
{
txtLocationName.Text = "";
txtSubAccountName.Text = "";
}
}
添加按钮工作得很好,似乎只是在刷新网格视图
我有以下在winforms应用程序中工作的示例诀窍在于dset.local
private void Form1_Load(object sender, EventArgs e)
{
var dset = Db.Tasks; // Db is my context.
DbSet<Task> qry = dset;
qry.Load();
bindingSource1.DataSource =dset.Local.ToBindingList();
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
Debug.Print(Db.Tasks.Count().ToString());
bindingSource1.EndEdit();
Db.SaveChanges();
}
经过昨晚的工作,我知道我缺少了一些东西。我最后是这样做的:
protected void btnDelete_Click(object sender, EventArgs e)
{
try
{
_context = new IMSDBContext();
switch (btnDelete.Text)
{
case DeleteButton:
if (txtLocationName.Text != null && txtSubAccountName.Text != null)
{
Location location = _context.Locations.ToList()
.First(x => x.Name == txtLocationName.Text && x.SubAccount == txtSubAccountName.Text);
_context.Locations.Remove(location);
_context.SaveChanges();
PopulateLocationGridView();
grdvwLocationList.SelectedIndex = 0;
RowSelected();
}
break;
case CancelButton:
Reload();
break;
}
}
catch (Exception ex)
{
lblLocationNameNotification.Text = ex.Message;
}
finally
{
if (_context != null)
{
_context.Dispose();
}
}
}
我曾尝试自己使用PopulateLocationGridView()和RowSelect()方法,但仍然遇到了问题。我最终放入了grdvwLocationList.SelectedIndex=0;在中,将所选索引设置在列表中的第一个索引上,而不是我刚刚删除的记录的索引上。那就是我遇到麻烦的地方。我以为SelectRow()会再次重新选择索引,但我不得不将其重置回另一个索引。如果有任何问题或意见,请随时联系。我仍在学习,希望能得到所有的建议。