开发者

LINQ projection to presentation model

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开发者_如何学C 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.


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()
}


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()
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜