希望有人能指出如何做到这一点:
我有一个使用Entity Framework的WinForms应用程序。我们例如通过提供BindingList的存储库将数据绑定到gridControl。
e.g。 (简化代码)
class ProductRepository {
public void LoadAll() {
_context.Products.Where(p => p.Deleted == false).Load();
}
public BindingList<T> GetBindingList() {
LoadAll();
return _context.Products.Local.ToBindingList();
}
}
class ProductListPresenter {
private void SetList() {
_view.SetList(productRepo.GetBindingList());
}
}
class ProductListView {
DeletedButton.Click += {
(bindingSource1.Current as Product).Deleted = 1;
gridControl1.Refresh();
};
}
但是:我只想显示未删除的产品(Product.Deleted == false)。可以在Repository Load()方法中对其进行过滤,但是当我将其绑定到我的控件时,如何过滤它呢?我不能做bindingSource1.RemoveCurrent(),因为它会完全擦除实体并将其标记为State.Deleted ..
这里要考虑的另一件事是:我在该表单中还有其他一些事情,只有当用户决定通过单击“保存”按钮保存更改时,我才需要在数据库中提交所有更改。我必须使用内存状态,直到用户明确保存更改。
有什么建议吗?在WinForms中使用EF以某种方式开始提高挫折程度..
答案 0 :(得分:0)
因为您要在逻辑上而不是物理上删除,所以您需要将删除事件冒泡到可以访问存储库或上下文的层,然后保存更改,然后将实体与上下文分离。例如:
class ProductListPresenter {
private void DeleteHandler(Object sender, EventArgs e)
{
productRepo.SaveChanges();
productRepo.DetachLogicallyDeletedEntities();
}
}
class ProductRepository
{
public void DetachLogicallyDeletedEntities()
{
foreach(var entity in _context.Products.Local
.Where(p=>p.Deleted == 1).ToList())
_context.Entry(entity).State = EntityState.Detached;
}
}
如果这是不合需要的,那么另一个选项是不绑定到上下文本地集合,而是绑定到独立的BindingList<>
,然后您可以直接在视图层中将其从列表中删除。
class ProductListView {
DeletedButton.Click += {
(bindingSource1.Current as Product).Deleted = 1;
bindingSource1.Remove(bindingSource1.Current);
};
}
第三种方法是创建IBindingListView
的实现,该实现保存并缓存本地ObservableCollection<>
上下文,并在本地集合所包含的内容与显示内容之间提供一个间接层。这样您就可以使用BindingSource.Filter
属性来提供过滤字符串。