繁体   English   中英

WPF中的实体框架POCO类和ViewModel

[英]Entity Framework POCO classes and ViewModels in WPF

如何使用最有效的方法向WPF提供这些功能,而无需实现INotifyPropertyChanged和其他WPF东西来解决数百个POCO模型的问题?

现在,我将EntityFramework与简单的POCO类和手工编写的ViewModels结合使用。

我的架构如下所示:

  • 视图
  • 视图模型
  • 储存库模式
  • WCF存储库或数据库存储库
  • 商业逻辑
  • 实体框架
  • POCO模型类

我的想法是:

  1. 使用AutomapperPOCO映射ViewModels类,然后再手动创建这些ViewModels。
  2. 使用T4生成基础ViewModels作为POCO类之前生成的包装,编写​​我自己的(或使用现有的解决方案) Instance resolver类以在EF中提供相同的功能(一个实例=数据库中的一条记录)。

我很困惑,因为我不喜欢自己的解决方案,它现在还不稳定,但是Automapper在映射中使用了反射

该怎么办? 您是否知道一些神奇的,真的很棒的工具来完成这些神奇的事情,并为我提供了添加和扩展ViewModel的灵活性?

我相信您假设:

  1. 通常您在ViewModel中创建Model对象的副本
  2. 通常,您在ViewModel的每个对象内实现INotifyPropertyChanged

我相信这两个假设都是错误的。 看下面的代码示例:

class Customer
{
  public int ID {get; set;}
  public string Name {get; set;}
}

class MyViewModel: INotifyPropertyChanged
{
  // Hook you repository (model) anyway you like (Singletons, Dependency Injection, etc)
  // For this sample I'm just crating a new one
  MyRepository repo = new MyRepository();

  public List<Customer> Customers 
  {
    get { return repo.Customers;}
  }

  public void ReadCustomers()
  {
    repo.ReadCustomers();
    InternalPropertyChanged("Customers");
  }

  public event PropertyChangedEventHandler PropertyChanged;
  protected void InternalPropertyChanged(string name)
  {
    if (PropertyChanged != null)
      PropertyChanged(this, new PropertyChangedEventArgs(name));
  }
}

class MyRepository
{
  private List<Customer> customers;
  public List<Customer> Customers
  {
    get { return customers; }
  }

  public void ReadCustomers()
  {
    // db is the Entity Framework Context
    // In the real word I would use a separate DAL object
    customers = db.Customers.ToList();
  }
}

客户是实体框架返回的列表。 ViewModel属性“客户”是一个简单的传递属性,它指向Model属性。

在此示例中,我不在Customer内部使用INotifyPropertyChanged。 我知道只有在用户调用ReadCustomers()时才能修改客户列表,因此在其中调用了PropertyChanged。

如果我需要为Customer类触发PropertyChanged通知,则可以直接在Customer类上实现INotifyPropertyChanged。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM