从集合ObservableCollection更新数据库

时间:2012-02-13 21:50:23

标签: c# wpf database mvvm observablecollection

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

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

我有以下代码:

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

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

                 ListCategories = categories.ToObservableCollection <Category>();

我的问题:

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

由于

1 个答案:

答案 0 :(得分: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。

您的可观察集合的设置应该在ctr:

中完成
ListCategories = categories.ToObservableCollection <Category>();

到此:

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