LINQ左边用OR运算符连接3个表

时间:2015-02-17 14:25:23

标签: c# linq sql-server-2008

我有这个SQL查询:

SELECT * FROM [CMS_MVC_PREPROD].[dbo].[T_MEMBER] m  
left outer join [CMS_MVC_PREPROD].[dbo].[T_COMPANY] c
ON m.Company_Id = c.Id
left outer join [CMS_MVC_PREPROD].[dbo].[T_ADRESSE] a  
ON m.Id = a.Member_Id OR a.Company_Id = c.Id

但我无法将其翻译成Linq

我特别对这条线路有些麻烦:

ON m.Id = a.Member_Id OR a.Company_Id = c.Id

编辑:我从Ehsan Sajjad尝试此查询

from m in db.Member
join c in db.T_Company on m.Company_Id equals c.Id into a
from c in a.DefaultIfEmpty()
from ta in db.T_Address
where m.Id == ta.Member_Id || ta.Company_Id == c.Id

但它只返回有地址且我想要所有成员的成员。也许它可以使用完整的连接

提前致谢

2 个答案:

答案 0 :(得分:1)

LINQ仅直接支持equi-joins。您必须使用不同的查询模式:

from m in db.MEMBER
//add join to "c" here
from a in (
     from a db.ADRESSE
     where m.Id == a.Member_Id || a.Company_Id == c.Id
     select a).DefaultIfEmpty()
select new { m, a }

只是一个草图。诀窍是在子查询上使用DefaultIfEmpty。 L2S和EF都可以将其转换为OUTER APPLY,相当于LEFT JOIN

答案 1 :(得分:0)

你可以用这种方式来使其发挥作用:

from m in db.Member
join c in db.T_Company on m.Company_Id equals c.Id into a
from c in a.DefaultIfEmpty()
from ta in db.T_Address
where m.Id == ta.Member_Id || ta.Company_Id == c.Id