2017-09-16 39 views
0

這是我正在工作的代碼我想知道當使用mvc圖表時這兩種情況是否可能?而如何去這樣做他們如何計算工作時間的總和和日期格式,只顯示mvc使用mvc圖表助手的月份

我控制器

public ActionResult CharterColumn() 
{ 
    ArrayList xValue = new ArrayList(); 
    ArrayList yValue = new ArrayList(); 

    var results = (from c in db.Timesheets select c); 

    results.ToList().ForEach(rs => xValue.Add(rs.Date)); 
    //I want to format this to show the only the months on the x axis 

    results.ToList().ForEach(rs => yValue.Add(rs.Hours)); 
    //And I want to calculate the sum of the hours for each month worked by a specific employee 

    new Chart(width: 800, height: 400, theme: ChartTheme.Yellow) 
    .AddTitle("Test") 
    .AddSeries("Default", chartType: "Column", xValue: xValue, yValues: yValue) 
    .Write("bmp"); 

    return null; 
} 

和我的觀點

<div> 
    <img src= "@Url.Action("CharterColumn")" alt="Chart"/> 
</div> 

回答

1

你可以把這些TimeSheet記錄的月和年這樣的:

DateTimeFormatInfo dtfi = new DateTimeFormatInfo(); 

// gets the records grouped based on Year and Month. 
// Creates an object of IEnumerable<IGrouping<>> type 
var groupedByMonth = result 
         .OrderByDescending(x => x.Date) 
         .GroupBy(x => new { x.Date.Year, x.Date.Month }).ToList(); 


// gets the months names in a list 
List<string> monthNames = groupedByMonth 
        .Select(a => dtfi.GetAbbreviatedMonthName(a.Key.Month)) 
        .ToList(); 

// gets the total hours per month 
List<int> hoursPerMonth = groupedByMonth 
         .Select(a => a.Sum(p => p.Hours)) 
         .ToList(); 


ArrayList xValue = new ArrayList(monthNames); 
ArrayList yValue = new ArrayList(hoursPerMonth); 

我正在使用DateTimeFormatInfo來獲取月份的名稱。您也可以做到這一點沒有這個:

List<string> monthNames = groupedByMonth 
        .Select(a => a.FirstOrDefault().Date.ToString("MMMM")) 
        .ToList(); 
+0

「System.NotSupportedException」類型的異常出現在EntityFramework.SqlServer.dll但在用戶代碼 其他信息沒有處理:LINQ到實體無法識別方法'System.String GetAbbreviatedMonthName(Int32)'方法,並且此方法不能轉換爲存儲表達式。嗨,我已經試過它得到這個錯誤 – Kimberly

+0

@Kimberly嘗試沒有'dtfi',如最後所述。我認爲你必須在linq查詢之前執行'.ToList()'。 – adiga

+0

附加信息:LINQ to Entities不識別方法'System.String ToString(System.String)'方法,並且此方法不能轉換爲存儲表達式。 – Kimberly

相關問題