LINQ右外连接具有多个连接条件

时间:2020-12-30 09:51:23

I'm trying to convert the following SQL to LINQ:

我正在尝试将以下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)

Basically what it's doing is grabbing data from the ClientCommands table from the database unless a record exists in the ClientCommandSessionProcessed table. I'm doing a right outer join to the ClientCommandSessionProcessed table (with two conditions in the on) and checking that the result from that join is null - if there is a record in that table, the query shouldn't return a result because that means it has been processed by that Session ID.

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

I have it almost done in LINQ, my only problem is, I can't seem to use more than one condition in my right outer join, and I don't think this would work properly if I stick my second condition in the where clause.

我几乎在LINQ中完成了它,我唯一的问题是,我似乎在右外连接中不能使用多个条件,如果我在where子句中坚持我的第二个条件,我认为这不会正常工作。

Here's what I have so far for LINQ:

这是我到目前为止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 };

Does anyone know if it's possible to add a second condition to a join? If not, is there a work-around for an issue like this?

有谁知道是否可以为连接添加第二个条件?如果没有,是否有解决这样的问题的办法?

Thank you!

1 个解决方案

#1


3  

You can do something like this:

你可以这样做:

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

#1


3  

You can do something like this:

你可以这样做:

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