2012-02-13 101 views
2

我目前正在与EnterpriseLibrary 5.0和MVVM使用的数据库:更新从集合的ObservableCollection

我有一个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>(); 

我的问题:

集合中的所有更改后,如何到u更新数据库?

感谢

+0

没有,只是一个简单的属性 – HichemSeeSharp 2012-02-13 21:54:36

回答

1

的正确方法是要有Repository模式后面的数据库访问层:

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

然后用您的域名类型分类实施这个(我假设这是一个域类型和不是由ORM生成的类型

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

然后设置依存性视图模型本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>(); 
} 
+0

感谢马克,通常我不会做调用数据库从ViewModel开始,我只是专注于这个问题,我想让所有东西都在眼前。我想说的是,如果可以的话,填充一个DataSet然后通过DataAdapter更新数据库 – HichemSeeSharp 2012-02-14 06:27:09