LINQ to Entity:多个连接条件

时间:2011-10-14 08:53:38

标签: linq linq-to-entities

关于LINQ和多个连接的帖子很多。 但是我没有找到任何我想要加入的解决方案。

SQL等价物将是这样的:

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查询之一

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......

如何添加日期和删除标志的附加条件? 如果我使用。条件,则将其视为内连接,而不是左连接。

5 个答案:

答案 0 :(得分:51)

另一种方式可能是

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}

答案 1 :(得分:15)

LINQ支持连接语法和旧的ANSI-82 WHERE语法。使用后者,您可以使用

执行内部联接中的搜索
var nowTime = DateTime.Now;
var query = from a in context.table1
            from b in context.table2
            where a.col1 == b.key1
                 && a.col2 == b.key2 
                 && b.from_date < nowTime
                 && b.deleted == false
            select ???;

对于外连接,我更喜欢使用where和select多种语言的混合语法。 (意识到LINQ查询中的顺序不需要模仿您在SQL中的操作,并且顺序更灵活。)

var nowTime = DateTime.Now;
var query = from b in context.table2
            from a1 in a.Where(a2 => 
                b.key1 = a.col && 
                b.key2 = a.col2 &&
                b.from_date < nowTime &&
                b.deleted == false).DefaultIfEmpty()
            select ???;

答案 2 :(得分:2)

我在匿名对象中命名属性时遇到问题:

var subscriptions = context.EmailSubscription.Join(context.EmailQueue,
                    es => new { es.Id, 9 },
                    eq => new { eq.EmailSubscriptionId, eq.EmailTemplateId },
                    (es, eq) => new { es.Id, eq.Id }
                ).ToList();

编译器不高兴,所以上面的回答可以帮助我弄清楚出了什么问题,这是我的工作解决方案。我花了一些时间才找到愚蠢的错误:):

var subscriptions = context.EmailSubscription.Join(context.EmailQueue,
                    es => new { EmailSubscriptionId = es.Id, EmailTemplateId  = 9 },
                    eq => new { eq.EmailSubscriptionId, eq.EmailTemplateId },
                    (es, eq) => new { es.Id, eq.Id }
                ).ToList();

答案 3 :(得分:1)

你能不能只用第二个查询过滤第一个结果集?

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
query = from x in query
        where ...

那会有用吗?

答案 4 :(得分:0)

除了@Muhammad Adeel Zahid答案外,您还可以使用一些条件,例如:

new
{
Key1 = ppl.PeopleId,
Key2 = true,
Key3 = true
}
equals
new
{
Key1 = y.PeopleId,
Key2 = !y.IsDeleted,
Key3 = (y.RelationshipType == 2 || y.RelationshipType == 4)
}