我正试图将下面的SQL查询转换为linq查询,但无法完成。如果另一个表中存在记录,请您通过连接和连接一个特殊字符(如"*")来帮助如何使用这种类型的case语句。请帮我怎么做。
Select Distinct A.MyID, Title + case when D.MyID is not null then ' *' else '' end as Title , MagTitle
FROM [MasterTitles] A left outer join TitleDetails D on A.[MyID] = D.[MyID]
WHERE [PropertyID] is not null
ORDER BY [Title]
还有更好的选择吗。我已经尝试过了,但无法弄清楚如何进行这种类型的LINQ查询。请有人在这个上指导我
我对查询做了一些更改:
var result = from x in context.MasterTitles
where x.PropertyID != null
orderby x.Title
select new { x.MyID, Title = x.TitleDetails.Any() ? x.Title + " *" : x.Title };
我已将left join
更改为EXISTS()
(.Any()
)。通过这种方式,我不需要Distinct()
试试这个方法:
var result = database.MasterTitles.Where(m => m.PropertyID != null)
.Join(database.TitleDetails, m => m.MyID, t => t.MyID, (m, t) => new { MyID = m.MyID, Title = m.Title + (t.MyID == null ? "" : "*" ), MagTitle = m.MagTitle })
.OrderBy(m => m.Title)
.Distinct();
我想你需要这样的东西,不确定LINQ是否可以为?:
生成脚本,如果不能在之前只使用AsEnumerable
和另一个select
(from a in dc.MasterTitles
join d in dc.TitleDetails on a.MyId equals d.MyId into adJoin
from ad in adJoin.DefaultIfEmpty()
order by a.Title
selec {a.MyId, Title = a.Title + (ad != null ? "*" : ""), a.MagTitle })
.Distinct()