1
我有兩個LinqToSql查詢返回結果集:聯盟兩個LINQ查詢
var grResults = (from g in ctx.GeneralRequests
join rt in ctx.RequestTypes on g.RequestTypeId equals rt.RequestTypeId
join sub in ctx.Logins on g.SubmitterStaffId equals sub.LoginId
join onb in ctx.Logins on g.OnBehalfOfStaffId equals onb.LoginId
where sub.GadId == gadId
select new
{
Status = "Submitted",
RequestId = g.GeneralRequestId,
Submitter = sub.UserName,
OnBehalf = (onb == null ? string.Empty : onb.UserName),
RequestType = (rt == null ? string.Empty : rt.Description),
ProjectName = (g == null ? string.Empty : g.ProjectName) ,
Comments = (g == null ? string.Empty : g.Comments),
LastUpdate = g.LastUpdateDate
});
var grdResults = (from gd in ctx.GeneralRequestDrafts
join rt in ctx.RequestTypes on gd.RequestTypeId equals rt.RequestTypeId
into tempRequestTypes
from rt1 in tempRequestTypes.DefaultIfEmpty()
join onb in ctx.Logins on gd.OnBehalfOfStaffId equals onb.LoginId
into tempOnBehalf
from onb1 in tempOnBehalf.DefaultIfEmpty()
join sub in ctx.Logins on gd.SubmitterStaffId equals sub.LoginId
where sub.GadId == gadId
select new
{
Status = "Draft",
RequestId = gd.GeneralRequestDraftId,
Submitter = sub.UserName,
OnBehalf = (onb1 == null ? string.Empty : onb1.UserName),
RequestType = (rt1 == null ? string.Empty : rt1.Description),
ProjectName = (gd.ProjectName == null ? string.Empty : gd.ProjectName),
Comments = (gd.Comments == null ? string.Empty : gd.Comments),
LastUpdate = gd.LastUpdateDate
});
問題是,當我嘗試聯合它們。
var results = grResults.Union(grdResults).OrderByDescending(r => r.LastUpdate);
即使兩個單獨的查詢都這樣做,它將不返回任何記錄。
檢查單個查詢上的'.ToList()'的結果,然後檢查聯合結果,以查看正在生成的SQL。 – StriplingWarrior
我不明白爲什麼聯盟不會有任何結果。這很奇怪。如果你不介意重複,你可以試試'.Concat'。無論如何,我認爲想要考慮包括LastUpdate可能非常困難。 Concat會更快,因爲它不必進行比較來嘗試刪除重複項。 –
@大衛,請接受下面的答案。 –