LINQ to Entity:多个连接条件 [英] LINQ to Entity : Multiple join conditions

查看:66
本文介绍了LINQ to Entity:多个连接条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

关于LINQ和多个联接的文章很多. 但是,我没有找到我想要建立的联接的任何解决方案.

There are numerous post regarding LINQ and multiple joins. I have however not found any solution to the join I'd like to make.

等效的SQL将是这样的:

The SQL equivalent would be something like this:

SELECT * FROM table1 a
LEFT JOIN table2 b ON a.col1 = b.key1 AND
a.col2 = b.key2 AND
b.from_date <= now() AND
b.deleted = 0;

这是我尝试过的众多linq查询之一

Here's one of the numerous linq queries I've attempted

var query = (from x in context.table1
             join y in context.table2 on new {x.col1, x.col2} equals {b.key1, b.key2} 
             into result
             from result......

如何添加日期和已删除标志的附加条件? 如果使用.Where条件,则将其视为内部联接,而不是左联接.

How may I add the additonal conditions of the date and deleted flag? If I use .Where conditions, then this is treated as a inner join, not a left join.

推荐答案

另一种方式可能是

var query = (from x in context.table1 
             join y in context.table2 on 
             new  {
                  Key1 = x.col1, 
                  Key2 = x.col2,
                  Key3 = true,
                  Key4 = true
                 }
             equals
             new {
                  Key1 = y.key1, 
                  Key2 =  y.key2,
                  Key3 = y.from_date< DateTime.Now,
                  Key4 = !y.deleted
                 }  
             into result
from r in result.DefaultIfEmpty()
select new  {x.Something, r.Something}

这篇关于LINQ to Entity:多个连接条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆