【问题标题】:Why a collection is not updated when the EF context changes are cancelled?为什么取消 EF 上下文更改时集合不更新?
【发布时间】:2014-11-12 15:38:25
【问题描述】:

我正在使用 .NET 4.0,我从数据库中获取结果,列表如下:

List<Customers> customers = context.Customers().ToList();

然后我将它分配给BindingSource

bindingSource1.DataSource = null;
bindingSource1.DataSource = customers;

bindingSource 用作网格视图的数据源,可以在其中执行更改 - 添加新记录、编辑、删除。 问题是当我想取消更改并将gridview中的数据恢复为数据库中的数据时。

我有以下代码可以取消更改:

private void cancelChanges()
    {
        // Refresh the modified entries
        var objectsModified = context.ObjectStateManager.GetObjectStateEntries(
                                System.Data.EntityState.Modified | System.Data.EntityState.Deleted)
                                .Select(e => e.Entity);

        context.RefreshFromDb(objectsModified);

        // Detach the added entries
        var objectsAdded = context.ObjectStateManager.GetObjectStateEntries(
                               System.Data.EntityState.Added)
                               .Select(e => e.Entity);

        foreach (var item in objectsAdded)
        {
            context.Customers().Detach(item as Customers);
        }
    }

我可以看到它有效,但问题是列表仍然保留旧记录(应该取消),因此也保留绑定源,最后它们仍然显示在网格中。

【问题讨论】:

    标签: c# winforms entity-framework entity-framework-4 bindingsource


    【解决方案1】:

    由于您是从上下文写入列表,因此您只会获得单向数据绑定。要做你想做的事,试试这样:

    context.Customers().Load();
    bindingSource1.DataSource = context.Customers.Local.ToBindingList();
    dataGridView1.DataSource = gridSource; 
    

    问题是您告诉数据库放弃更改,但由于此时您的列表仍绑定到控件并与数据库分离,因此您看不到反映的更改。或者,您可以在调用 CancelChanges 后再次调用 customers = context.Customers().ToList() 以重新加载数据库中的当前数据。

    【讨论】:

    猜你喜欢
    • 2013-08-14
    • 1970-01-01
    • 2020-11-25
    • 2013-11-03
    • 2011-10-26
    • 2013-09-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多