C# 从集合ObservableCollection更新数据库

C# 从集合ObservableCollection更新数据库,c#,wpf,database,mvvm,observablecollection,C#,Wpf,Database,Mvvm,Observablecollection,我目前正在使用EnterpriseLibrary 5.0和MVVM: 我有一个绑定到可编辑组合框的ObservableCollection ListCategories属性(我可以添加/删除/编辑类别): 我有以下代码: public ObservableCollection<Category> ListCategories { get { return listCategories;

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

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

我有以下代码:

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

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

                 ListCategories = categories.ToObservableCollection <Category>();
公共可观察收集列表类别
{
得到
{
返回列表类别;
}
设置
{
listCategories=值;
}
}
var categories=sdb.executesproccessor(“获取类别列表”);
ListCategories=categories.ToObservableCollection();
我的问题:

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


谢谢

正确的方法是在以下存储库模式后面有一个DB访问层:

public interface IRepository<T>
{
   IEnumerable<T> GetAll();
   T GetById(int id);
   void Save(T saveThis);
   void Delete(T deleteThis);
}
然后从ViewModel中处理此依赖关系,ViewModel不应该直接调用数据库,这似乎是您的意思

您的代码:

sdb.ExecuteSprocAccessor <Category> ("Get_Categories_List");
sdb.executesprocacessor(“获取类别列表”);
应位于存储库的GetAll()中。将其移出ViewModel

应在ctr中设置可观察集合:

ListCategories = categories.ToObservableCollection <Category>();
ListCategories=categories.ToObservableCollection();
为此:

public ViewModel(ICategoryRepository categoryRepo)
{
    _categoryRepo = categoryRepo;
    var categories = _categoryRepo.GetAll();
    ListCategories = categories.ToObservableCollection <Category>();
}
公共视图模型(ICategoryRepository类别REPO)
{
_categoryRepo=categoryRepo;
var categories=_categoryRepo.GetAll();
ListCategories=categories.ToObservableCollection();
}

谢谢Mark,通常我不会从ViewModel调用数据库,我只是专注于这个问题,我想让一切都在我的眼皮底下。我想说的是通过填充数据集进行更新,然后通过DataAdapter更新数据库(如果可能的话)。当然,这个解释很好@MarkW,切中要害。将项目添加到集合/存储库应该如何工作?我假设继续调用GetAll()刷新视图代价很高,那么我们可以手动添加到存储库中,然后添加ObservableCollection吗?
ListCategories = categories.ToObservableCollection <Category>();
public ViewModel(ICategoryRepository categoryRepo)
{
    _categoryRepo = categoryRepo;
    var categories = _categoryRepo.GetAll();
    ListCategories = categories.ToObservableCollection <Category>();
}