我需要创建一个取消按钮,它将回滚自上次上下文保存以来的所有更改。我得到的是按钮点击后的回滚。但是,DataGridView并没有反映出这种变化。如果我退出该程序,我可以看到没有数据被更改。
我得到了以下表格(我没有在“输出”窗口中看到任何错误)但是,我读到的所有内容都表示将上下文包装在using语句中。在这种情况下,这仍然适用吗?我已经使用了Rollback并在一个保存方法中提交了try / catch但是这个平面没有看起来不对。如果我生成另一个表单,它会添加到当前事务中吗?
/// <summary>
/// </summary>
public partial class Form2 : Form
{
/// <summary>
/// </summary>
private TestContext _context;
/// <summary>
/// </summary>
private DbContextTransaction _transaction;
/// <summary>
/// </summary>
public Form2()
{
InitializeComponent();
}
/// <summary>
/// </summary>
/// <param name="e"></param>
protected override void OnClosing(CancelEventArgs e)
{
base.OnClosing(e);
_transaction.Rollback();
_context.Dispose();
}
/// <summary>
/// </summary>
/// <param name="e"></param>
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
_context = new TestContext();
_transaction = _context.Database.BeginTransaction();
SetupDataGridView();
}
/// <summary>
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnCancel_Click(object sender, EventArgs e)
{
_transaction.Rollback();
_context = new TestContext();
SetupDataGridView();
_transaction = _context.Database.BeginTransaction();
}
/// <summary>
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnSave_Click(object sender, EventArgs e)
{
Validate();
PersonDataGridView.CommitEdit(DataGridViewDataErrorContexts.Commit);
_context.SaveChanges();
_transaction.Commit();
PersonBindingSource.ResetBindings(true);
_transaction = _context.Database.BeginTransaction();
}
/// <summary>
/// </summary>
private void SetupDataGridView()
{
_context.People.Load();
ObservableCollection<Person> people = _context.People.Local;
PersonBindingSource.DataSource = people.ToBindingList();
PersonBindingSource.RaiseListChangedEvents = true;
PersonDataGridView.AutoGenerateColumns = false;
PersonDataGridView.DataSource = PersonBindingSource;
}
}