【问题标题】:LINQ right outer join with multiple conditions in joinLINQ右外连接,连接中有多个条件
【发布时间】:2013-06-07 18:02:50
【问题描述】:

我正在尝试将以下 SQL 转换为 LINQ:

select * from ClientCommands as cc 
    join ClientCommandTypes as cct on cc.ClientCommandTypeID = cct.ClientCommandTypeID
    right outer join ClientCommandSessionProcessed as ccsp 
        -- This next line is the one I'm having trouble with:
        on cc.ClientCommandID = ccsp.ClientCommandID and cc.ClientSessionID = @ClientSessionID
where
    ccsp.ClientCommandSessionProcessedID is null and
    cc.StartDate < getdate() and
    cc.DeactivatedDate > getdate() and
    (cc.ClientAppID is null or cc.ClientAppID == @ClientAppID)

基本上,它所做的是从数据库中的 ClientCommands 表中获取数据,除非 ClientCommandSessionProcessed 表中存在记录。我正在对 ClientCommandSessionProcessed 表进行right outer 连接(on 中有两个条件)并检查该连接的结果是否为空 - 如果该表中有记录,则查询不应返回结果,因为这意味着它已被该会话 ID 处理。

我几乎在 LINQ 中完成了它,我唯一的问题是,我似乎无法在我的 right outer join 中使用多个条件,而且我认为如果我坚持我的第二个条件,这将无法正常工作where 子句。

这是我目前对 LINQ 的了解:

var clientCommands = from cc in db.ClientCommands
    join cct in db.ClientCommandTypes on cc.ClientCommandTypeID equals cct.ClientCommandTypeID
    join ccsp in db.ClientCommandSessionProcesseds 
        // How do I add a second condition here?
        on cc.ClientCommandID equals ccsp.ClientCommandID into ccspR
    from ccspRR in ccspR.DefaultIfEmpty()
    where 
    ccspRR == null &&
    cc.StartDate < DateTime.Now  && 
    cc.DeactivatedDate > DateTime.Now &&
    (cc.ClientAppID == null || cc.ClientAppID == clientApp.ClientAppId)
    select new { cc, cct };

有谁知道是否可以在联接中添加第二个条件?如果没有,是否有解决此类问题的方法?

谢谢!

【问题讨论】:

    标签: sql linq tsql linq-to-sql


    【解决方案1】:

    你可以这样做:

    var result = from x in table1
             join y in table2
             on new { x.field1, x.field2 } equals new { y.field1, y.field2 }
    

    【讨论】:

    • 谢谢neontapir,这看起来像我需要的。我会试一试,很快就会回来报告。
    • 谢谢你,这太完美了
    猜你喜欢
    • 2010-11-10
    • 2012-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-25
    • 2011-01-10
    • 1970-01-01
    • 2011-12-07
    相关资源
    最近更新 更多