2012-02-13 108 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

相關問題