c# - 从集合 ObservableCollection 更新数据库

标签 c# wpf database mvvm observablecollection

我目前正在使用 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/

相关文章:

c# - 旋转 BitmapImage

c# - ASP.NET Identity 2在保存扩展应用程序用户时插入重复数据或保存两次

wpf - DataGrid 选定项绑定(bind)

php - 检索Mysql数据失败...为什么?

mysql - Ubuntu : SQL time is not the same as current OS timezone

c# - 如何使此参数访问语法成为可能?

c# - 什么让我困惑....NET 语言是 Windows(独立)应用程序的主流语言吗?

wpf - 如何将命令行为附加到 ListView 中的 TextBox?

WPF MediaElement - 视频暂停和位置重置时图像不会更新

python - 交易中的交易