LINQ to Entities中的多个Left OUTER OUTER连接

时间:2015-07-29 10:43:49

标签: c# .net linq entity-framework linq-to-entities

使用Linq To Entities如何重现以下SQL查询?

SELECT  m.MaterialId, m.MaterialName, m.MaterialTitle, vv.NearestTXDate, c.ChannelName
FROM GB_Material m
LEFT OUTER JOIN WF_VideoVersion vv on vv.MaterialID = m.MaterialID
LEFT OUTER JOIN SP_ScheduleEvent se on se.MaterialName = m.MaterialName
INNER JOIN SP_Schedule s on s.ScheduleID = se.ScheduleID
INNER JOIN GB_Channel c on c.ChannelID = s.ChannelID
WHERE LOWER(m.MaterialName) like '%foo%' OR LOWER(m.MaterialTitle) like '%foo%'  
编辑:我已经排除了对此的答案,因为答案会产生此SQL查询所做的确切结果,但请注意原始SQL查询会产生不需要的交叉连接,我在编写时没有意识到

2 个答案:

答案 0 :(得分:1)

(from m in context.GB_Material
join vv in context.WF_VideoVersion  on new {m.MaterialID }
                                               equals new { vv.MaterialID } into vv_join
                                             from vv in vv_join.DefaultIfEmpty()
join se in context.SP_ScheduleEvent  on new {m.MaterialName }
                                               equals new { se.MaterialName } into se_join
                                             from se in se_join.DefaultIfEmpty()
 join s in context.SP_Schedule on new {se.ScheduleID } equals new { s.ScheduleID}
join c in context.GB_Channel on new { s.ChannelID } equals new { c.ChannelID }

                                             where
                                              m.MaterialName.ToLower().Contains("foo") || m.MaterialTitle.ToLower() .Contains("foo")

                                             select new
                                             {
                                                 m.MaterialId, m.MaterialName, m.MaterialTitle, vv.NearestTXDate, c.ChannelName

                                             })

答案 1 :(得分:0)

尝试此查询

var objlist =(from m in Contex.GB_Material
from vv in Contex.WF_VideoVersion.Where(x=>x.MaterialID =m.MaterialID ).DefaultIfEmpty()
from se in Contex.SP_ScheduleEvent.Where(x=>x.MaterialName =m.MaterialName ).DefaultIfEmpty()
from s in Contex.SP_Schedule .Where(x=>x.ScheduleID =se.ScheduleID)
from c in Contex.GB_Channel .Where(x=>x.ChannelID =s.ChannelID )
WHERE m.MaterialName.ToLower().Contains("foo") || m.MaterialTitle.ToLower() .Contains("foo")
select new{  m.MaterialId, m.MaterialName, m.MaterialTitle, vv.NearestTXDate, c.ChannelName}).ToList();