Kma*_*man 35 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;
Run Code Online (Sandbox Code Playgroud)
这是我尝试过的众多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......
Run Code Online (Sandbox Code Playgroud)
我怎样才能添加日期和删除标志的附加条件?如果我使用.Where条件,则将其视为内连接,而不是左连接.
Muh*_*hid 60
另一种方式可能是
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}
Run Code Online (Sandbox Code Playgroud)
Jim*_*ley 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 ???;
Run Code Online (Sandbox Code Playgroud)
对于外连接,我更喜欢使用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 ???;
Run Code Online (Sandbox Code Playgroud)
我在匿名对象中命名属性时遇到问题:
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();
Run Code Online (Sandbox Code Playgroud)
编译器不高兴,所以上面的答案可以帮助我找出问题所在,这是我的工作解决方案。我花了一些时间才发现愚蠢的错误:):
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();
Run Code Online (Sandbox Code Playgroud)