2013-01-31 68 views
1

大多數教程都沒有真正涵蓋這一點。他們只是說你的實體鏈接到控制器,你就完成了。將實體組合到ViewModels中並使用實體框架

在我的商業模式中,我有客戶,我有客戶聯繫人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; } 
} 
+0

有趣的問題。我沒有發現自己使用1個模型來處理所有的垃圾。他們都有不同的模型。甚至在進入延遲加載vs渴望和選擇列表下拉菜單之類的問題之前......像手機一樣簡單(我經常分爲3個字段進行創建和編輯,然後重新組合。 –

+0

@DaveA對不起,我不理解如果這就是你的意思 – Preston

+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; } 
    } 

這真是你來構建您的視圖模型的方式,將滿足需求你的具體項目。

+0

您能否包括控制器和視圖如何工作這個?實體框架不起作用。 – Preston

+0

同時downvoted和接受? –

+2

這是我不喜歡的一件事 - 無理由狙擊 –