【问题标题】:Update the database from a collection ObservableCollection从集合 ObservableCollection 更新数据库
【发布时间】:2012-02-13 21:50:22
【问题描述】:

我目前正在使用 EnterpriseLibrary 5.0 和 MVVM:

我有一个ObservableCollection ListCategories<Category> 属性绑定到一个可编辑的组合框(我可以添加/删除/编辑类别):

我有以下代码:

public ObservableCollection<Category> ListCategories
        {
            get
            {
                return listCategories;
            }

            set
            {
                listCategories = value;
            }
        }
    var categories = sdb.ExecuteSprocAccessor <Category> ("Get_Categories_List");

                 ListCategories = categories.ToObservableCollection <Category>();

我的问题:

在集合中进行所有更改后,如何更新回数据库?

谢谢

【问题讨论】:

    标签: c# wpf database mvvm observablecollection


    【解决方案1】:

    正确的方法是在以下 Repository 模式后面有一个 DB Access 层:

    public interface IRepository<T>
    {
       IEnumerable<T> GetAll();
       T GetById(int id);
       void Save(T saveThis);
       void Delete(T deleteThis);
    }
    

    然后使用您的域类型 Category 来实现它(我假设这是一个域类型,而不是由 ORM 生成的类型。

    public interface ICategoryRepository : IRepository<Category>
    {
        // add any methods that are needed to act on this specific repo
    }
    

    然后将ViewModel中的依赖设置为这个ICategoryRepository;

    private readonly ICategoryRepository _categoryRepo;
    
    public ViewModel(ICategoryRepository categoryRepo)
    {
        _categoryRepo = categoryRepo;
    }
    

    然后根据您的 ViewModel 的这种依赖关系采取行动,您的 ViewModel 不应该直接调用数据库,这就是您所暗示的。

    你的代码:

    sdb.ExecuteSprocAccessor <Category> ("Get_Categories_List");
    

    应该驻留在存储库的 GetAll() 中。将其移出 ViewModel。

    你的 observable 集合的设置应该在 ctr 中完成:

    ListCategories = categories.ToObservableCollection <Category>();
    

    到这里:

    public ViewModel(ICategoryRepository categoryRepo)
    {
        _categoryRepo = categoryRepo;
        var categories = _categoryRepo.GetAll();
        ListCategories = categories.ToObservableCollection <Category>();
    }
    

    【讨论】:

    • 感谢 Mark,通常我不会从 ViewModel 调用数据库,我只是专注于这个问题,我希望一切都在眼前。我想说的是通过填充 DataSet 进行更新,然后如果可能的话,通过 DataAdapter 更新数据库
    • 这个解释很好@MarkW,而且切中要害。将项目添加到集合/存储库应该如何工作?我认为继续调用 GetAll() 来刷新视图的成本很高,所以我们可以手动添加到 Repository 然后再添加到 ObservableCollection 吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-10
    • 2013-09-07
    相关资源
    最近更新 更多