In a recent EF Code First project we were attempting to optimize some Linq queries using different techniques (don't worry its not premature). One common way to optimize a linq query is to convert more of the expression from Linq-to-Objects to almost all Linq-to-Entities side, which is generally faster than mixing Linq-to-Objects and Linq-to-Entities with lazy loading.
I've read how to create linq expressions for most queries that are translatable to Linq-To-Entities, but I'm not sure how to do this with the object initializer syntax.
Take this example:
return results.Select(x => new { Name = x.FullName });
From the falling example Person
class:
public class Person
{
public string FullName
{
get { return FirstName + " " + LastName; }
}
public string FirstName { get; set; }
public string LastName { get; set; }
}
Now I can make the first expression into a Linq-to-Entity friendly expression by converting it to:
return results.Select(x => new { Name = x.FirstName + " " + x.LastName});
But this kind of sucks bad because I'm duplicating the logic for the FullName. Now you can say this doesn't matter for such a trivial example, but its not hard to imagine a case with a much more complex read-only property.
Anyway I'm trying to figure out if there is a way to do something like this:
return results.Select(x => new { Name = Person.FullNameExpression(x) });
Can anyone tell me if something like this is possible in Linq-to-entities, without using Linq-to-objects?
If this isn't possible, what's the closest I can get to preventing from repeating the logic for readonly properties on my entites?