EF 不要在 BindingSource 中使用 IQueryable 保存

EF Don't save using IQueryable in BindingSource

我已经使用 DbSet 创建了代码优先上下文 属性

我使用 Windows 表格。如果我绑定如下:

_context.Schedules.Load();
scheduleBindingSource.DataSource = _context.Schedules.Local.ToBindingList();

一切正常,当我保存如下时:

this.Validate();
scheduleBindingSource.EndEdit();
_context.SaveChanges();

数据持续存在;但是当我像这样绑定数据时:

var res = _context.Schedules.Where(k => k.EmployeeName.Equals(employeeComboBox.Text)).ToList();
scheduleBindingSource.DataSource = res;

当我保存数据时不持久!

我认为 ToList() 方法不好,但我找不到替代方法来将 BindingList 连接到上下文中的本地数据集。

谢谢,

安德里亚

你可以试试这个:

_context.Schedules.Where(k => k.EmployeeName.Equals(employeeComboBox.Text)).Load();
scheduleBindingSource.DataSource = _context.Schedules.Local.ToBindingList();

那应该只带符合条件的时间表。当您在 Where 方法之后调用 Load 方法时,它只会将满足条件的记录带到内存中。稍后,当您调用 Local 属性 时,它会给您一个 ObservableCollection<Schedule>,其中包含 DbContext 当前跟踪的所有对象,您将成为您之前加载的元素。最后,当您调用 ToBindingList 扩展方法时,它将 returns 一个 BindingList<Schedule> 与给定的 ObservableCollection<Schedules>.

保持同步

造成数据不持久的原因是DataGridView(或BindingSource)没有将刚刚添加的行的新实例添加到上下文中。

所以我禁用了 AllowUserToAddRow 属性(现在我正在使用 BindingNavigator 添加按钮)

并实现了这两个事件如下:

private void scheduleBindingSource_AddingNew(object sender, AddingNewEventArgs e)
{
    _scheduleAdding = true;
}

private void scheduleBindingSource_CurrentChanged(object sender, EventArgs e)
{
    if (_scheduleAdding)
    {
        Schedule s = (Schedule)scheduleBindingSource.Current;
        s.EmployeeName = employeeComboBox.Text;
        s.From = new DateTime(dateTimePicker1.Value.Year, dateTimePicker1.Value.Month, 1);
        _context.Schedules.Add(s);
        _scheduleAdding = false;
    }
}