[英]objectcontext & dbcontext differences when binding
I have been using ObjectContext in my projects, but now I'm trying DbContext, I found some differences that I don't understand when binding to a datasource, for example 我在项目中一直使用ObjectContext,但是现在尝试DbContext时,发现绑定到数据源时有些我不理解的差异。
I bind datasource like this 我这样绑定数据源
DbSet<Client> Clients = ctx.Client;
Clients.Load();
bsClients.DataSource = Clients().Local.ToBindingList();
bsClientPhones.DataSource = ((Client)bsClients.Current).Phone; // this line doesn't work
When I bind "bsClientPhones" like that, the grid doesn't show changes when add or delete, until I save and reload data. 当我像这样绑定“ bsClientPhones”时,添加或删除时网格不会显示更改,直到我保存并重新加载数据为止。 I can't convert it to Local or Bindinglist. 我无法将其转换为Local或Bindinglist。
I don't know if this is the right way to use DbContext Please could someone guide me? 我不知道这是使用DbContext的正确方法吗?有人可以指导我吗? I have been reading many documentation but I'm lost. 我读过许多文档,但迷路了。
You will have to implement ObservableCollection at entity level and provide the same to your grids. 您将必须在实体级别实现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();
After every change, you need to call this.categoryDataGridView.Refresh();
每次更改后,您需要调用this.categoryDataGridView.Refresh();
Here is the quick demo I can give with the DataGridView. 这是我可以使用DataGridView进行的快速演示。 The same will apply to GridView for Web form. 这同样适用于GridView for Web表单。
https://github.com/codebased/tm/tree/master/WindowsFormTestConsole https://github.com/codebased/tm/tree/master/WindowsFormTestConsole
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.