【问题标题】:'Generic' ViewModel“通用”视图模型
【发布时间】:2010-01-18 17:31:30
【问题描述】:

使用 EF 4,我有几个“业务”实体的子类型(客户、供应商、运输公司等)。他们确实需要是子类型。我正在构建一个通用视图模型,它调用一个可以访问通用存储库的服务。

因为我有 4 个子类型,所以最好有一个用于所有这些的“通用”视图模型。问题当然是我必须将特定类型调用到我的通用存储库中,例如:

BusinessToRetrieve = _repository
    .LoadEntity<Customer>(o => o.CustomerID == customerID);

能够调用&lt;SomethingElse&gt; 会很好,somethingElse 是其中一个或其他子类型),否则我将不得不创建 4 个几乎相同的 viemodel,这当然看起来很浪费!子类型实体名称可用于视图模型,但我一直无法弄清楚如何使上述调用将其转换为类型。实现我想要的一个问题是,传入的 lambda 表达式可能无法在“通用”调用上解决?

【问题讨论】:

    标签: entity-framework mvvm repository generics entity-framework-4


    【解决方案1】:

    听起来您需要熟悉generics。首先,您将能够编写如下代码:

    class ViewModel<T> where T : Business {
        public void DoSomething(Func<T, bool> predicate) {
            BusinessToRetreive = _repository.LoadEntity<T>(predicate);
        }
    }
    

    那么你可以说:

    ViewModel<Customer> c = new ViewModel<Customer>();
    c.DoSomething(o => o.CustomerID == customerID);
    

    【讨论】:

      【解决方案2】:

      我不确定这是否是您想要的,但您可能对 MicroModels 感兴趣

      public class EditCustomerModel : MicroModel
      {
          public EditCustomerModel(Customer customer, 
                                   CustomerRepository customerRepository)
          {
              Property(() => customer.FirstName);
              Property(() => customer.LastName).Named("Surname");
              Property("FullName", () => string.Format("{0} {1}", 
                                                 customer.FirstName, 
                                                 customer.LastName));
              Command("Save", () => customerRepository.Save(customer));
          }
      }
      

      【讨论】:

        猜你喜欢
        • 2011-06-10
        • 2017-12-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-04-13
        • 1970-01-01
        • 2012-10-25
        • 1970-01-01
        相关资源
        最近更新 更多