【问题标题】:Combining Entities into ViewModels and using Entity Framework将实体组合到 ViewModel 中并使用实体框架
【发布时间】:2013-01-31 18:40:57
【问题描述】:

大多数教程根本没有真正涵盖这一点。他们只是说将您的实体链接到控制器,您就完成了。

在我的业务模型中,我有客户,并且我有 1 个客户到 >1 个客户联系人。如何为这些创建一个视图模型,以允许从同一视图编辑/创建/任何内容?

public class Customer
{
    public Customer()
    {
        this.CustomerContacts = new List<CustomerContact>();
        this.Systems = new List<System>();
        this.CreatedByCustomerTickets = new List<Ticket>();
        this.CustomerTickets = new List<Ticket>();
    }

    public long CustomerID { get; set; }
    public Nullable<bool> BusinessCustomer { get; set; }
    public string CustomerName { get; set; }
    public string CustomerNotes { get; set; }
    public virtual ICollection<CustomerContact> CustomerContacts { get; set; }
    public virtual ICollection<System> Systems { get; set; }
    public virtual ICollection<Ticket> CreatedByCustomerTickets { get; set; }
    public virtual ICollection<Ticket> CustomerTickets { get; set; }
}

public class CustomerContact
{
    public long CustomerContactID { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int Phone { get; set; }
    public string AddressLine1 { get; set; }
    public string AddressLine2 { get; set; }
    public string City { get; set; }
    public string State { get; set; }
    public Nullable<int> Zip { get; set; }
    public Nullable<long> CustomerID { get; set; }
    public string Email { get; set; }
    public bool PromotionalEmails { get; set; }
    public virtual Customer Customer { get; set; }
}

【问题讨论】:

  • 有趣的问题。我没有发现自己对所有的杂物都使用 1 个模型。他们都有不同的模型。甚至在遇到诸如延迟加载与急切和选择下拉列表之类的问题之前……就像电话一样简单(我经常分成 3 个字段进行创建和编辑,然后重新组合。
  • @DaveA 对不起,我不明白。如果这就是您的意思,它们实际上在它们自己的模型和 CS 文件中。
  • 绝对是断开连接,但您可能有严格的要求。请解释您为什么要从同一视图执行创建、读取和更新
  • 这看起来很合适。一个客户只有 2 条数据,如果没有一些联系信息,这些数据几乎是无用的。
  • 我同意数据关系简单。我回避在屏幕中组合功能。

标签: c# asp.net-mvc asp.net-mvc-3 entity-framework


【解决方案1】:

我先从这个开始

public class CustomerViewModel
{
  public Customer Customer {get; set;}
  public CustomerContact CustomerContact {get; set;}
}

然后从那里开始工作。

如果您不需要域对象的所有属性,您可以考虑更多类似的东西:

public class CustomerViewModel
    {
       public long CustomerID { get; set; }
       public ICollection<CustomerContact> CustomerContacts { get; set; }
    }

完全由您决定以一种满足您特定项目需求的方式构建视图模型。

【讨论】:

  • 您能否介绍一下控制器和视图如何与它一起工作?实体框架不适用于此。
  • 这是我不喜欢 SO 的一件事——无缘无故的狙击
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-05
  • 2010-09-29
  • 1970-01-01
  • 1970-01-01
  • 2010-11-28
相关资源
最近更新 更多