我有一個LINQ查詢的問題,不知道如何解決它:/group by join and aggregate(linq)
我有兩個表。一個是屬性,第二個是來自屬性的行,但我需要從行中總結小時並將其分配給屬性;無法解釋得非常好;)這是我的查詢,我試圖創建:
var query = (from ta in session.db.TimesheetAttributes
join tr in session.db.TimesheetRows on ta.Id equals tr.TimesheetAttributesId into tempTR
from ttr in tempTR.DefaultIfEmpty()
group ttr by new { ta.TimesheetId, ta.Date, ta.SickNote, ta.Vacation, ta.OccasionVacation } into g
select new
{
Id = g.Key.TimesheetId,
Date = g.Key.Date,
WeekDay = g.Key.Date.ToString("dddd", new CultureInfo("pl-PL")),
Description = String.Format("{0:dd/MM/yyyy}", g.Key.Date),
SickNote = g.Key.SickNote,
Vacation = g.Key.Vacation,
OccasionVacation = g.Key.OccasionVacation,
Hours = String.Format("{0:HH:mm}", (new DateTime(g.Aggregate(TimeSpan.Zero, (subtotal, t) => subtotal + (t.DateTo - t.DateFrom)).Ticks)))
}).OrderBy(c=>c.Date).ToList();
的問題是,不是每個屬性的有行,這就是爲什麼我試圖使用DefaultIfEmpty(),但這個查詢不工作:(
我的舊的查詢工作,但我的ORM,使每一行一個新的查詢,所以如果我有1000個TimesheetAttributes它使1000種選擇:/
這裏是我的舊的查詢:
var query = (from c in session.db.TimesheetAttributes
where ((c.Active == true)
&& (c.Timesheet.Active == true)
&& (c.ValidFrom <= validDate)
&& (c.ValidTo > validDate)
&& (c.Timesheet.ContactPersonId == session.ContactPersonAttributes.ContactPersonId))
select new
{
Id = c.TimesheetId,
c.Date,
WeekDay = c.Date.ToString("dddd", new CultureInfo("pl-PL")),
Description = String.Format("{0:dd/MM/yyyy}", c.Date),
Hours = String.Format("{0:HH:mm}", (new DateTime((c.TimesheetRows.Aggregate(TimeSpan.Zero, (subtotal, t) => subtotal + (t.DateTo - t.DateFrom)).Ticks)))),
c.SickNote,
c.Vacation,
c.OccasionVacation
}).OrderBy(c => c.Date).ToList();
編輯:
這是我得到的異常:「異常已通過調用的目標引發異常」 的InnerException:「對象引用不設置到對象的實例」
你能告訴我具體什麼不起作用嗎?你得到的錯誤/例外,或者你總是得到空的結果... – Frederiek
我沒有從這個問題得到任何東西可以PLZ顯示查詢的一些結果 –
ive編輯我的帖子 – Cfaniak