I started out with this question, which I sort of answered there, and now I’m asking the more fundamental question here. I’ve simplified the query down to this:
var q = from ent in LinqUtils.GetTable<Entity>()
from tel in ent.Telephones.DefaultIfEmpty()
select new {
Name = ent.FormattedName,
Tel = tel != null ? tel.FormattedNumber : "" // this is what causes the error
};
tel.FormattedNumber is a property that combines the Number and Extension fields into a neatly formatted string. And here’s the error that results:
System.InvalidOperationException: Could not translate expression 'Table(Entity).SelectMany(ent => ent.Telephones.DefaultIfEmpty(), (ent, tel) => new <>f__AnonymousType0`2(Name = ent.FormattedName, Tel = IIF((tel != null), tel.FormattedNumber, "")))' into SQL and could not treat it as a local expression.
If I change the reference above from FormattedNumber to just plain Number, everything works fine.
But I do want the formatted number to display nicely in my list. What do you recommend as the neatest, cleanest way of doing so?
You could use
AsEnumerableon the entity, but that would force it to bring back all the columns (even if not used); perhaps instead something like:where
FormatNumberis some method that takes the two and merges them, presumably re-used from your other (property) code.With LINQ-to-SQL, another option is to expose a UDF on the data-context that does the formatting inside the database; a slightly different example:
(which will do the work at the database; whether or not that is a good idea ;-p)