2016-07-07 64 views
1

我有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一樣。謝謝。

+4

您應該使用視圖模型來表示要在視圖中的信息的最終狀態,你不應該試圖以EF實體直接綁定到視圖。 –

+0

感謝您的評論,我將使用視圖模型。 – Rob

回答

1

你不需要使用視圖模型,但我可能會推薦這樣做。我更願意在視圖外進行所有處理,因此您需要在控制器中進行計算,並將總時間分配給視圖模型中的屬性。但是,這是很容易做到同樣的事情在視圖本身,就這樣添加了一些看法:

@{ 
    var jobs = projects.Jobs; 
    var totalTime = jobs.Sum(job => job.Logs.Sum(x => x.totaltime)); 
} 

<p>Total time is @totalTime</p> 
+0

謝謝,我想我會使用一個viewmodel,但很高興知道我可以這樣做。 – Rob

1

使用視圖模型要做到這一點,我強烈建議在控制好建築做業務所以:

控制器:

var jobs = db.JobsList.ToList(); 
var totalTime = jobs.Sum(x => x.Logs).Sum(x => x.totaltime)); 
相關問題