我目前正在使用 EnterpriseLibrary 5.0 和 MVVM:
我有一个 ObservableCollection ListCategories<Category>
绑定(bind)到可编辑 ComboBox 的属性(我可以添加/删除/编辑类别):
我有以下代码:
public ObservableCollection<Category> ListCategories
{
get
{
return listCategories;
}
set
{
listCategories = value;
}
}
var categories = sdb.ExecuteSprocAccessor <Category> ("Get_Categories_List");
ListCategories = categories.ToObservableCollection <Category>();
我的问题:
在对集合进行所有更改之后,如何更新回数据库?
谢谢
最佳答案
正确的方法是在存储库模式后面有一个数据库访问层:
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
}
然后在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>();
}
关于c# - 从集合 ObservableCollection 更新数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9268564/