我在SQL中有2个表.
Table 1
Step Id
Step Name
Table 2
Profile Id
Step Id
Completed
Run Code Online (Sandbox Code Playgroud)
即使表2中没有匹配,我也想返回以下结果:
Results
Table1.Step Id
Table1.Step Name
Table2.Profile Id
Table2.Completed
Run Code Online (Sandbox Code Playgroud)
我在SQL中执行此操作的方式如下:
select * from [Table 1] t1
left join [Table 2] t2
on t1.Step Id = t2.Step Id
Run Code Online (Sandbox Code Playgroud)
这产生了我期望的结果.
当我把它翻译成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();
}
Run Code Online (Sandbox Code Playgroud)
它可以工作,但像JOIN而不是左连接.我只收到匹配的结果.
此外,UserCompletion是我从此方法返回的对象.
我已经在这里敲了几天......任何帮助都将不胜感激.
你也可以尝试这个(假设us.Completed是布尔值):
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
};
Run Code Online (Sandbox Code Playgroud)
这不会变成sql中的连接,而是嵌套的select语句,如下所示:
select
StepId, Headline, ProfileId,
isnull((select top(1) Completed from userStep where StepId = Id), 0) as Completed
from step
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
4233 次 |
最近记录: |