Domanda
Ho 2 tabelle in SQL.
Table 1
Step Id
Step Name
Table 2
Profile Id
Step Id
Completed
Vorrei restituire i seguenti risultati anche se non c'è corrispondenza nella tabella 2:
Results
Table1.Step Id
Table1.Step Name
Table2.Profile Id
Table2.Completed
Il modo in cui lo sto facendo in SQL è il seguente:
select * from [Table 1] t1
left join [Table 2] t2
on t1.Step Id = t2.Step Id
Questo produce i risultati che mi aspetto.
Quando traduco questo in linq:
public static List<UserCompletion> GetStepCompletion(string category, string profileid) {
List<Step> step = GetSteps(category);
List<UserStep> userStep = GetUserSteps(category, profileId);
var q = from s in step
join us in userStep
on s.Id equals us.StepId
select new UserCompletion
{
StepId = s.Id,
Headline = s.StepName,
ProfileId = us.ProfileId
Completed= us.Completed
};
return q.ToList();
}
Funziona ma come un JOIN non un join sinistro. Ricevo solo risultati corrispondenti.
Inoltre, UserCompletion è un oggetto che ritorno da questo metodo.
Ci sto sbattendo la testa da qualche giorno ... qualsiasi aiuto sarebbe apprezzato.
Soluzione
Puoi anche provare questo (supponendo che il completamento sia booleano):
var q = from s in step
let us = (from i in userStep where s.Id = i.StepId).SingleOrDefault()
select new UserCompletion
{
StepId = s.Id,
Headline = s.StepName,
ProfileId = us.ProfileId
Completed = us == null ? false : us.Completed
};
Questo non si trasformerà in un join in sql, ma un'istruzione select nidificata in questo modo:
select
StepId, Headline, ProfileId,
isnull((select top(1) Completed from userStep where StepId = Id), 0) as Completed
from step
Altri suggerimenti
Prova qualcosa sulla falsariga di quanto segue:
var q = from s in step
join us in userStep
on s.Id equals us.StepId into tmpjoin
from x in tmpjoin.DefaultIfEmpty()
select new UserCompletion { ... }
Trovato.
Sembra che debba aggiungere una valutazione sull'elemento che "può" essere nullo.
Ho aggiunto quanto segue alla mia selezione
Completed = (x == null) ? String.Empty : x.Completed