Linq to Entities骑自行车左外连接

时间:2015-07-08 10:26:33

标签: sql linq linq-to-entities

我遇到了Linq对实体的问题。

图: enter image description here

Linq to entities查询(尚未完成):

void BootstrapperApplication_DetectComplete(object sender, DetectCompleteEventArgs e)
            {
                string balCondtionMessages = string.Empty;
                bool balConditionStatus = true;
                foreach (var balCondition in bootAppData.BundleData.BalConditions)
                {
                    if (!model.BootstrapperApplication.Engine.EvaluateCondition(balCondition.Condition))
                    {
                        balConditionStatus = false;
                        if (!String.IsNullOrEmpty(balCondtionMessages))
                        {
                            balCondtionMessages = balCondtionMessages + '\n' + "- " + balCondition.Message;
                        }
                        else
                            balCondtionMessages = "- " + balCondition.Message;
                    }


                }

                if (!balConditionStatus) 
                {
                 SetbalConditionMsg(balCondtionMessages);
                }    
        }

生成的SQL:

from a in Anlaesse 
join b in Beurteilung on a.AnlassID equals b.AnlassID into ab 
from b in ab.DefaultIfEmpty() 
join r in Rangliste on a.AnlassID equals r.AnlassId 
join p in Pony on r.PonyId equals p.PonyID into rp 
from p in rp.DefaultIfEmpty() 
where a.AnlassID == 67 
select new 
    {         
    BeurteilungId = b.BeurteilungID == null ? 0 : b.BeurteilungID, 
    PonyID = p.PonyID == null ? 0 : p.PonyID, 
    Name = p.Name, 
    PonyName1 = r.PonyName1, 
    AnlassId = a.AnlassID == null ? 0 : a.AnlassID 
    } 

问题是我无法在Pony和Beurteilung之间添加左外连接,因为我的查询中已经“使用”了所有表。没有这个,结果是错误的,因为它为每个小马返回所有Beurteilung。

1 个答案:

答案 0 :(得分:0)

我们假设你想要加入Pony加入Beurteilung。我们假设两者都有PonyId属性。像这样的子句将充当内连接:

where p.PonyId == b.PonyId

这样的子句将充当左连接。

where b == null || p.PonyId == b.PonyId

然而,您发现这很难,因为它看起来并不像您正在使用实体框架。您是否已映射任何导航属性或集合?如果你还没有添加它们,因为这是EF的一点。如果你有,那么你就不需要使用内连接或左连接;你只需遍历导航属性。