views:

1133

answers:

1

I have a fairly complex Linq query:

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 : "",
        };

This query is returning me an SQL error:

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

Yes, in triplicate. That's an obvious indicator that the problem with the query is being repeated 3 times i.e. in the 3 different types of phone number.

According to the SQL server documentation, this comes from a malformed query. But this is Linq, for heaven's sake! How can it be malforming the query?

Aside from the main answer, I'd also appreciate any comments you may have about optimizing my query...

Thanks!

+1  A: 

Solved it myself, and here it is for anyone else's benefit.

The devil is in the select clause at the end, specifically:

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

That FormattedNumber property is a calculated field based on the Number and Extension properties of the EntityTelephone object. When I replace FormattedNumber with Number, everything works fine.

The best solution to this problem is found here.

Shaul