【问题标题】:WPF - Where to add CRUD actions in MVVMWPF - 在 MVVM 中添加 CRUD 操作的位置
【发布时间】:2020-02-04 21:02:08
【问题描述】:

我是 WPF 新手,我正在尝试在我的 WPF 应用程序中实现 MVVM 模型。我有这个场景:一个客户模型、一个客户视图、一个 CUstomersViewModel 和一个 Dbcontext 类。

模型 Customers.cs

 public partial class Customers
 {
     public int Id { get; set; }
     public string Customer { get; set; }     
 }

MyDbContext.cs

 public partial class MyDbContext: DbContext
    {
        public MyDbContext()
        {
        }

        public MyDbContext(DbContextOptions<MyDbContext> options)
            : base(options)
        {
        }

        public virtual DbSet<Customers> Customers { get; set; }
        public virtual DbSet<Users> Users{ get; set; }



        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            if (!optionsBuilder.IsConfigured)
            {
                   // ..............
            }
        }

CustomersViewModel.cs

 class CustomersViewModel
    {
        public ObservableCollection<Customers> Customers { get; set; }

        public CustomersViewModel()
        {

            using (MyDbContext db = new MyDbContext())
            {
                Customers = new ObservableCollection<Customers>(db.Customers.ToList());
            }
        }
    }

在我看来,我将 ViewModel 绑定到一个组合框:

<Window.Resources>
        <ViewModels:CustomersViewModel x:Key="CustomerViewModel"/>
    </Window.Resources>
...

  <ComboBox x:Name="cboCustomers" Grid.Row="2" 
                          DataContext="{StaticResource CustomerViewModel}" 
                          ItemsSource="{Binding Customers}" 
                          DisplayMemberPath="Customer"/>

这很好用。但是(这可能是一个愚蠢的问题),如果我想添加更多查询,例如按 Id 检索客户、按特定列对客户进行分组或更新客户,我需要在哪里添加这些?

   Customers = new ObservableCollection<Customers>(db.Customers.Where(....))..

在 Viewmodel 类中? ViewModel 的构造函数,目前获取所有客户。

【问题讨论】:

  • 创建一个新类,例如 DBLayer 类,您将在其中拥有所有这些方法。让您的 ViewModel 实例化此类的一个对象并在需要时使用其方法

标签: wpf mvvm


【解决方案1】:

如果我想添加更多查询,例如按 ID 检索客户、按特定列对客户进行分组或更新客户,我需要在哪里添加这些?

例如,在您注入视图模型的服务中,例如:

class CustomersViewModel
{
    private readonly ICustomerService _customerService;

    public ObservableCollection<Customers> Customers { get; set; }

    public CustomersViewModel(ICustomerService customerService)
    {
        _customerService = customerService;
    }
}

然后,视图模型可以根据用户交互(例如按钮单击)调用服务上的操作。

服务实现负责连接到数据库,例如通过数据访问层使用实体框架。

【讨论】:

  • 嗨,感谢您为我指明了正确的方向。我已经使用我需要的所有方法创建了服务,但我仍然不确定如何从 ViewModel 调用这些方法。你能告诉我一个如何做到这一点的例子吗?
  • @Leño77:您只需使用注入视图模型的引用调用服务的方法,例如_customerService.GetCustomers()。何时何地执行此操作是另一个主题,但要翻译您的原始代码示例,您可以在构造函数中完成。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-07-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多