将实体组合到ViewModel并使用Entity Framework

时间:2013-01-31 18:40:57

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

大多数教程根本没有涵盖这一点。他们只是说你的实体与控制器联系起来就已经完成了。

在我的商业模式中,我有客户,我有客户联系人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 个答案:

答案 0 :(得分: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; }
    }

您可以通过满足特定项目需求的方式构建视图模型。