【问题标题】:mvvm repository filteringmvvm 存储库过滤
【发布时间】:2011-05-22 20:08:50
【问题描述】:

我有一些主要基于 Josh Smith 的 msdn article 的详细课程。它的代码很棒,尤其是作为示例,但让我想知道如何最好地处理您需要某个存储库子集的情况。

所以 Josh 有一个名为 AllCustomersViewModel 的类,代码如下:

    public AllCustomersViewModel(CustomerRepository customerRepository)
    {
        if (customerRepository == null) throw new ArgumentNullException("customerRepository");

        // Populate the AllCustomers collection with CustomerViewModels.
         _allCustomers = _customerRepository
            .GetCustomers()
            .Select(cust => new CustomerViewModel(cust, _customerRepository))
            .ToList();
   }

您如何解决需要 PreferredCustomers、ExCustomers、LocalCustomers 等的情况?

他的代码向我建议每个 ViewModel 类,并在该类中硬编码存储库的过滤。

或者将可选过滤器与存储库一起传递到 ViewModel 的方法?

您的代码如何解决这个特殊问题?

顺便说一句,有没有人有链接或很好的例子来展示如何使用 SpeciaficationPattern 或 IQueryable 来解决这样的问题?

干杯,
浆果

【问题讨论】:

  • 乔希现在在这里花一点时间。你可能会很幸运。

标签: c# mvvm repository-pattern iqueryable specification-pattern


【解决方案1】:

一个选项(可能是最干净的)是将这些方法简单地添加到CustomerRepository - 例如GetPreferredCustomers()GetLocalCustomers() 等。

另外,你真的应该反对抽象,所以应该将ICustomerRepository 传递给你的视图模型构造函数。这将您的视图模型代码与您的具体客户存储库(在本例中是从 XML 文件读取的存储库)分离,并且可以轻松交换实现,例如用于单元测试。

正如您提到的,另一个选项是让您的存储库公开IQueryable<T>。如果您很高兴与 IQueryable 绑定,并且确信任何数据访问实现都将支持 LINQ 提供程序,那么这将提供很好的灵活性。请参阅here 了解更多信息。

就个人而言,我更喜欢第一种选择,尤其是对于更大规模的应用程序。

【讨论】:

  • 同意为存储库使用一个接口,我确实使用了一个。但这还不够;例如,如果 GetLocalCustomers() 需要一个参数,也许是一个邮政编码来定义什么是本地的 - that 去哪里?将查看您的链接,并且还将查看 Udi Dahn 的 this one。干杯
  • 这将在您的 ICustomerRepository 接口和具体实现上进行
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-02
  • 1970-01-01
  • 2017-01-10
  • 2020-07-12
  • 1970-01-01
相关资源
最近更新 更多