“当EXISTS没有引入子查询时,只能在选择列表中指定一个表达式。”

时间:2009-08-11 20:29:54

标签: c# linq linq-to-sql

我有一个相当复杂的Linq查询:

var q = from eiods in LinqUtils.GetTable<EIOfficialDesignee>()
        let eiodent = eiods.Entity
        join tel in LinqUtils.GetTable<EntityTelephone>()
        on new { EntityID = eiodent.ID, TelephoneType = EntityTelephone.TTelephone.Office } equals new { tel.EntityID, tel.TelephoneType }
        into Tel
        let Tel1 = Tel.FirstOrDefault()
        join fax in LinqUtils.GetTable<EntityTelephone>()
        on new { EntityID = eiodent.ID, TelephoneType = EntityTelephone.TTelephone.Fax } equals new { fax.EntityID, fax.TelephoneType }
        into Fax
        let Fax1 = Fax.FirstOrDefault()
        join cell in LinqUtils.GetTable<EntityTelephone>().DefaultIfEmpty()
        on new { EntityID = eiodent.ID, TelephoneType = EntityTelephone.TTelephone.Mobile } equals new { cell.EntityID, cell.TelephoneType }
        into Mobile
        let Mobile1 = Mobile.FirstOrDefault()
        where eiods.ID == CurrentEIPatient.EIOfficialDesigneeID
        select new {
          ID = eiods.ID,
          EIODName = eiodent.FormattedName,
          Phone = Tel1 != null ? Tel1.FormattedNumber : "",
          Fax = Fax1 != null ? Fax1.FormattedNumber : "",
          Cellphone = Mobile1 != null ? Mobile1.FormattedNumber : "",
        };

此查询返回一个SQL错误:

Only one expression can be specified in the select list when the subquery is not introduced with EXISTS
Only one expression can be specified in the select list when the subquery is not introduced with EXISTS
Only one expression can be specified in the select list when the subquery is not introduced with EXISTS

是的,一式三份。这显然表明查询问题重复了3次,即3种不同类型的电话号码。

根据SQL Server文档,这来自格式错误的查询。但这是Linq,为了天堂的缘故!如何使查询变形?

除了主要答案之外,我还非常感谢您对优化我的查询的任何评论...

谢谢!

1 个答案:

答案 0 :(得分:2)

我自己解决了,这是为了其他任何人的利益。

魔鬼在最后的select子句中,特别是:

Phone = Tel1 != null ? Tel1.FormattedNumber : "",
Fax = Fax1 != null ? Fax1.FormattedNumber : "",
Cellphone = Mobile1 != null ? Mobile1.FormattedNumber : "",

FormattedNumber属性是基于Number对象的ExtensionEntityTelephone属性的计算字段。当我用FormattedNumber替换Number时,一切正常。

找到此问题的最佳解决方案here