为什么我需要在SaveChanges之前更改绑定源位置

Ran*_*ndy 8 c# entity-framework bindingsource winforms

我有一个小型的WinForms演示应用程序.其中一个表格是我的添加新人表格.我使用了详细信息视图而不是DataGridView我的数据源.当我输入数据并单击导航器上的保存按钮时,没有任何更改,但是我在表单中放置了一个MovePrevious和一个MoveNext后,一切都按预期工作.AddNewLoad

public partial class AddPersonForm : Form
{
    private readonly DemoContext _context;

    public AddPersonForm()
    {
        _context = new DemoContext();
        InitializeComponent();
    }

    protected override void OnLoad(EventArgs e)
    {
        _context.People.Load();

        personBindingSource.DataSource = _context.People.Local.ToBindingList();

        personBindingSource.AddNew();
        personBindingSource.MovePrevious();
        personBindingSource.MoveNext();

        base.OnLoad(e);
    }

    private void personBindingNavigatorSaveItem_Click(object sender, EventArgs e)
    {
        int changes = _context.SaveChanges();
        Debug.WriteLine("# of changes: " + changes);
    }
}
Run Code Online (Sandbox Code Playgroud)

为什么我需要在识别更改并保存之前切换BindingSource位置?

Rez*_*aei 4

您不需要更改位置,实际上您需要调用BindingSource 的EndEdit来将挂起的更改应用于基础数据源。

更改头寸会导致基础货币管理器调用EndCurrentEdit,这就是EndEdit绑定源方法为您所做的事情。

所以这就是你通常想要做的:

try
{
    this.Validate();
    bindingSource1.EndEdit();
    //Save data by dbContext.SaveChange or tableAdapter.Update
    //Set the dialog result or show a success message
}
catch (Exception ex)
{
    //Handle the exception, log it and/or show a failure message
}
Run Code Online (Sandbox Code Playgroud)