2017-10-04 34 views
-1

我對C#Razor MVC項目中的MySQL數據庫有以下LINQ查詢。LINQ中沒有TruncateTime()的日期分組

private Dictionary<DateTime?, int> getOrderQuantityDict(DateTime start, DateTime end, int siteCode) 
{ 
    return (from o in thisDataEntities.this_table 
     where o.created_at >= start 
     && o.created_at <= end 
     && o.store_id == siteCode 
     select new { OrderDate = o.created_at, Id = o.entity_id}) 
     .GroupBy(q => q.OrderDate) 
     .ToDictionary(q => q.Key, q => q.Count()); 
} 

我需要按天分組。現在q.OrderDate有小時,分鐘和秒鐘。分組時,我需要忽略這些。

棘手的部分:我需要這樣做沒有TruncateTime()。當我們的主機移動我們的數據庫時,由於某種原因,我們失去了使用TruncateTime()的能力。我們的主機在這個問題上的幫助不大,我希望有一個解決方法是可能的。

+0

您可以嘗試:'.GroupBy(q => q.OrderDate.Date)' –

+1

@JeroenvanLangen - 我害怕Linq to Entities將無法將屬性'.Date'轉換爲SQL – Fabio

回答

1

沒有測試過,但下面可以幫助你:

return (from o in thisDataEntities.this_table 
    where o.created_at >= start 
    && o.created_at <= end 
    && o.store_id == siteCode 
    select new { OrderDate = o.created_at, Id = o.entity_id}) 
    .AsEnumerable() //Once this is executed, the database will return the result of the query and any other statement after this will be ran locally so TruncateTime will not be an issue 
    .GroupBy(q => q.OrderDate) 
    .ToDictionary(q => q.Key, q => q.Count()); 
+0

有幾個小細節錯誤,但使用'.AsEnumerable()'讓我運行C#邏輯的想法是絕對關鍵的。我會建議一個符合我使用的編輯。非常感謝! – Goose

0

您可以日期轉換爲字符串,並分組基於日期的字符串表示。

return 
    thisDataEntities.this_table 
        .Where(o => o.created_at >= start) 
        .Where(o => o.created_at <= end) 
        .Where(o => o.store_id == siteCode) 
        .Select(o => new 
          { 
           OrderDate = o.created_at, 
           Id = o.entity_id, 
           OrderDateFormatted = 
            SqlFunctions.DateName("yyyy", o.created_at) + "-" + 
            SqlFunctions.DateName("mm", o.created_at) + "-" + 
            SqlFunctions.DateName("dd", o.created_at) 
          }) 
        .GroupBy(n => n.OrderDateFormatted) // format "2017-10-03" 
        .ToDictionary(g => g.First().OrderDate, g => g.Count()); 

上面的方法應該在數據庫端發生。當然只有在支持GroupBy的情況下。