我是实体框架的新手,我正在研究数据库的第一个场景。 我正在处理示例crud操作,我想删除详细信息视图中的当前对象。
目前我只能删除视图中的第一个对象
private void btnDelete_Click(object sender, RoutedEventArgs e)
{
Branch delBranch = null;
if (muTime.Branches.Count() > 0)
{
delBranch = muTime.Branches.First();
}
else
{
MessageBox.Show("No Records to delete");
return;
}
muTime.Branches.Remove(delBranch);
muTime.SaveChanges();
MessageBox.Show("Deleted " + muTime.Branches.ToString());
branchViewSource.View.Refresh();
}
答案 0 :(得分:0)
您需要将您想要的记录带入跟踪。您当前的代码总是要删除First()分支。您需要识别指向要删除的分支的控件(网格?)或变量。
private void btnDelete_Click(object sender, RoutedEventArgs e)
{
// get the id you want to delete from grid, other control or somewhere else
DataGridViewRow row = this.dataGridView1.SelectedRows[0];
var branchId = row.Cells["Id"].Value
var branchToRemove = muTime.Branches.Find(branchId); // or whatever key is
if (branchToRemove == null)
{
MessageBox.Show("No Records to delete");
return;
}
muTime.Branches.Remove(branchToRemove);
muTime.SaveChanges();
MessageBox.Show("Deleted " + branchToRemove.ToString()); // or some property that identifies?
branchViewSource.View.Refresh();
}