【问题标题】:Linq to Entities - Left outer join with Lambda expressionLinq to Entities - 使用 Lambda 表达式的左外连接
【发布时间】:2011-10-27 11:43:59
【问题描述】:

我有这个查询,但我无法在 Lambda 表达式中找到它。

select * from NewsVersion nv
left outer join ChangeProcess cp on cp.DocumentId = nv.NewsId and cp.EndDate is null
where nv.NewsId = 'B2301B7F-D37E-4CF5-9392-01844564BFCC'

有人有想法吗?

谢谢

【问题讨论】:

    标签: .net c#-4.0 lambda linq-to-entities


    【解决方案1】:

    我不是 100% 确定并且有点困惑为什么 Thomas Levesque 认为这不是一个等值连接(毕竟 NewsId == DocumentId 是一个相等比较),但我不明白为什么这不应该工作:

    var query =
    from nv in db.NewsVersion
    join cp in db.ChangeProcess on nv.NewsId equals cp.DocumentId into joined
    from j in joined.Where(x => x.EndDate == null).DefaultIfEmpty()
    where nv.NewsId = "B2301B7F-D37E-4CF5-9392-01844564BFCC"
    select new { NewsVersion = nv, ChangeProcess = j };
    

    编辑:根据 OP 的评论更正

    【讨论】:

    • 我只是对您的查询进行了一些更改,它正在工作!谢谢!从 j 中加入。Where(x => x.EndDate == null).DefaultIfEmpty()
    • 谢谢,那你能把它标记为答案吗?这样我就会因为试图帮助你而获得一些声誉。
    【解决方案2】:

    这样的事情怎么样...

    var query =
        from nv in NewsVersion
        from cp in ChangeProcess.DefaultIfEmpty()
        where nv.NewsId == cp.DocumentId && cp.EndDate == null && 
           nv.NewsId = "B2301B7F-D37E-4CF5-9392-01844564BFCC"
        select new { ... }
    

    【讨论】:

    • 如果更改流程结束日期不为空,此查询将不会返回新闻版本。
    【解决方案3】:

    因为它不是等值连接,所以你不能使用join 关键字,但你仍然可以这样做:

    var query =
        from nv in db.NewsVersion
        from cp in db.ChangeProcess.Where(c => nv.NewsId == cp.DocumentId && c.EndDate == null).DefaultIfEmpty()
        where nv.NewsId = "B2301B7F-D37E-4CF5-9392-01844564BFCC"
        select new { NewsVersion = nv, ChangeProcess = cp };
    

    【讨论】:

    • 如果更改过程结束日期不为空,此查询将不会返回新闻版本。
    • @sebascomeau,你说得对,我错过了。我更新了我的答案
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-22
    • 2011-09-20
    相关资源
    最近更新 更多