I’m trying to solve a problem similar to the one described here
Initializing strongly typed objects in LINQ to Entities
only from totally the opposite direction. I have a number of functions in my repository, all of which return identically shaped data. The issue is my projection code:
select new pocoClass
{
// complex projection that is several pages long includes grabbing a graph of data
}
at the moment it exists for each query in the repository. I’d tried moving it into an object initializer, but that gives me the dreaded “Only parameterless constructors and initializers are supported in LINQ to Entities.” issue.
I did try splitting into two queries
var candidates = (from thing in _entities.whatever
where (complex.stuff==true)
select thing);
var final = (from thing in candidates.AsEnumerable()
let x = thing.ITEMS.Where(blah=>blah.blah==param)
let y = x.OTHERITEMS.FirstOrDefault()
select new pocoClass(thing,x,y);
but here final is always null and the code in new pocoClass is never called. I’ve included the let x & y in the above because these always vary between each use of the projection.
So, do I have to go back to multiple copies of my projection or is there another way out of this ?
I’m not sure it this is usable for you, but what I often do is create projection methods that take an
IQueryableand return anIQueryableto translate from a domain object to a DTO. They look much like this:This allows me to have this projection in a single place. From several places in my business layer I call such a method.
There are a few things to note, though:
IQueryable. In that case I return an array of DTOs.I hope this helps.