简体   繁体   English

Linq To SQL LEFT JOIN(OR语句)

[英]Linq To SQL LEFT JOIN (OR Statement)

I want to rewrite this simple MS SQL Query in Linq To SQL: 我想用Linq To SQL重写这个简单的MS SQL查询:

SELECT * FROM Table1 T1
    LEFT JOIN Table2 T2 ON T1.ID = T2.Table1ID OR T1.FirstName = T2.FirstName

How do I rewrite this in Linq To SQL? 如何在Linq To SQL中重写它?

Try this, although I don't know how well Linq-to-SQL will translate it: 尝试一下,尽管我不知道Linq-to-SQL将如何翻译它:

from t1 in ctx.Table1
from t2 in ctx.Table2
              .Where(t => t1.ID == t.Table1ID ||
                          t1.FirstName == t.Firstname)
              .DefaultIfEmpty()
select new {t1, t2}

I don't believe this can be done because I don't think you can do the OR part of the join. 我不认为这可以做到,因为我不认为您可以执行联接的“或”部分。 The way you do joins in L2S would be (roughly) 您加入L2S的方式大概是

join .. on
new {
    T1.ID,
    T1.FirstName
} equals new {
    T2.Table1ID,
    T2.FirstName
}

but that would match both. 但这将两者都匹配。

Only thing I can think you could do would be to do some sort of subquery in there. 我认为您唯一可以做的就是在其中执行某种子查询。 But that's probably not what you're looking for. 但这可能不是您想要的。 Sklivvz's suggestion may be the best one. Sklivvz的建议可能是最好的。

This is an inner join. 这是一个内部联接。

from t1 in ctx.Table1
from t2 in ctx.Table2
where t1.ID == t2.Table1ID ||
      t1.FirstName == t2.Firstname
select t1

To get a left join it looks like you use DefaultIfEmpty() , per MSDN . 要获得左连接,就好像您根据MSDN使用DefaultIfEmpty()一样。

from t1 in ctx.Table1
from t2 in ctx.Table2.DefaultIfEmpty()
where t1.ID == t2.Table1ID ||
      t1.FirstName == t2.Firstname
select t1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM