objectcontext&;绑定时的dbcontext差异

本文关键字:dbcontext 差异 定时 绑定 amp objectcontext | 更新日期: 2023-09-27 18:24:45

我一直在项目中使用ObjectContext,但现在我正在尝试DbContext,在绑定到数据源时发现了一些我不理解的差异,例如

使用DbContext

我像这个一样绑定数据源

DbSet<Client> Clients = ctx.Client;
Clients.Load();
bsClients.DataSource = Clients().Local.ToBindingList();
bsClientPhones.DataSource = ((Client)bsClients.Current).Phone; // this line doesn't work

当我像那样绑定"bsClientPhones"时,网格在添加或删除时不会显示更改,直到我保存并重新加载数据。我无法将其转换为Local或Bindinglist。

我不知道这是否是使用DbContext的正确方法请有人给我指路好吗?我一直在阅读许多文档,但我迷路了。

objectcontext&;绑定时的dbcontext差异

您必须在实体级别实现ObservableCollection,并将其提供给您的网格。

   public class ObservableListSource<T> : ObservableCollection<T>, IListSource
        where T : class
    {
        private IBindingList _bindingList;
        bool IListSource.ContainsListCollection { get { return false; } }
        IList IListSource.GetList()
        {
            return _bindingList ?? (_bindingList = this.ToBindingList());
        }
    } 
this.categoryBindingSource.DataSource =
                _context.Categories.Local.ToBindingList();

每次更改后,您需要调用this.categoryDataGridView.Refresh();

以下是我可以使用DataGridView进行的快速演示。这同样适用于Web表单的GridView。

https://github.com/codebased/tm/tree/master/WindowsFormTestConsole