我有3種型號:在MVC中以簡單的層次結構模型,最佳實踐是什麼?
項目
public int ProjectID { get; set; }
public string Description { get; set; }
public string UserID { get; set; }
[ForeignKey("UserID")]
public virtual ApplicationUser User { get; set; }
public virtual ICollection<Job> Jobs { get; set; }
喬布斯
public int JobID { get; set; }
public int ProjectID { get; set; }
public string Title { get; set; }
public string Jobdescription { get; set; }
public string UserID { get; set; }
[ForeignKey("UserID")]
public virtual ApplicationUser User { get; set; }
public virtual Project Projects { get; set; }
public virtual ICollection<Log> Logs { get; set; }
public virtual ICollection<Assignment> Assignments { get; set; }
日誌
public int LogID { get; set; }
public int JobID { get; set; }
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:yyyy-MM-dd HH:mm}")]
public DateTime Logstart { get; set; }
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:yyyy-MM-dd HH:mm}")]
public DateTime Logend { get; set; }
public int totaltime { get; set; }
public string Notes { get; set; }
public string UserID { get; set; }
[ForeignKey("UserID")]
public virtual ApplicationUser User { get; set; }
public virtual Job Job { get; set; }
我想有例如在我的項目索引視圖的總和所有'總時間'爲每個項目的所有日誌。在我工作的索引頁,我可以很容易地在我看來foreach循環這樣的總結中的總量做到這一點:
@TimeSpan.FromMinutes(item.Logs.Sum(i => i.totaltime))
但是我不知道該怎麼做同樣的事情,我的項目頁面上沒有或者創造一個視圖模型或將ProjectID鍵添加到日誌模型,以便我可以在項目索引頁上爲項目執行上述操作。
我可以使用這個每個項目的第一份工作得到TOTALTIME值:
@TimeSpan.FromMinutes(item.Jobs.Sum(i => i.Logs.First().totaltime))
但是我不知道我該怎麼寫這個總結所有爲每個作業「totaltimes」的。
我想知道的是什麼是做到這一點的最好方法。我是否需要在項目模型與作業模型相關的方式下創建視圖模型或將關係添加到我的日誌模型中的項目模型中。這些方法有哪些缺點或問題可能會丟失?當然,有一種簡單的方法可以讓我使用上面使用的東西來實現項目的「總時間」?
我就像你剛纔試圖慢慢學習MVC一樣。謝謝。
您應該使用視圖模型來表示要在視圖中的信息的最終狀態,你不應該試圖以EF實體直接綁定到視圖。 –
感謝您的評論,我將使用視圖模型。 – Rob