views:

130

answers:

2

I'm pretty new to LINQ and a lot of modern data-driven application design techniques in general, so this may be a pretty basic question.

I'm trying to create a projection of a couple different Entity Framework entities to a simple presentation model. Let's say I have the entites Parent (properties are ID, Name, Age) and Child (properties are ID, Name, Age, with a reference to a Parent). I want to project these to PresentationParent and PresentationChild, where all the properties are the same, but PresentationParent has a List. How would I do this in LINQ?

from p in entities.Parent
select new PresentationParent
{
    ID = p.ID,
    Name = p.Name,
    Age = p.Age,
    Children = [[?? What goes here ??]]
}

Is this on the right track at all? I can only seem to find examples of simple, flat projections.

+4  A: 

Something like this:

from p in entities.Parent
select new PresentationParent {
    ID = p.ID,
    Name = p.Name,
    Age = p.Age,
    Children = (from c in entities.Child
                where c.Parent == p
                select new PresentationChild {
                    ID = c.ID,
                    Name = c.Name,
                    Age = c.Age
                }).ToList()
}

However, your entities should come pre-configured with the necessary foreign key relationships already, so you could do something like this:

from p in entities.Parent
select new PresentationParent {
    ID = p.ID,
    Name = p.Name,
    Age = p.Age,
    Children = p.Children.ToList()
}

Of course, that would return all the properties of each child, so you might want to project the children anyway:

from p in entities.Parent
select new PresentationParent {
    ID = p.ID,
    Name = p.Name,
    Age = p.Age,
    Children = (from c in p.Children
                select new PresentationChild {
                    ID = c.ID,
                    Name = c.Name,
                    Age = c.Age
                }).ToList()
}
Christian Hayter
This compiles but fails when you try to enumerate the result set - it complains that LINQ to Entities "does not recognize" the ToList method, and "this method cannot be translated into a store expression." It works if I use LINQ to SQL instead of EF though.
nlawalker
I'm not in a position to try this myself right now, but you could try moving the `ToList` method to enclose the entire outer query instead. That should give the L2E provider more flexibility to translate the query into valid SQL.
Christian Hayter
A: 

Another alternative, if the relationship isn't set up enough to have the accessor available:

from p in entities.Parent
from c in entities.Children on p.ID equals c.parentID into children
select new PresentationParent
{
    ID = p.ID,
    Name = p.Name,
    Age = p.Age,
    Children = children.ToList()
}
Frank Schwieterman
Won't children.ToList() create a list of Child objects, not PresentationChild objects?
nlawalker