2

我对 LINQ 和许多现代数据驱动的应用程序设计技术很陌生,所以这可能是一个非常基本的问题。

我正在尝试将几个不同的实体框架实体投影到一个简单的表示模型。假设我有实体 Parent(属性是 ID、Name、Age)和 Child(属性是 ID、Name、Age,并引用 Parent)。我想将这些投影到 PresentationParent 和 PresentationChild,所有属性都相同,但 PresentationParent 有一个列表。我将如何在 LINQ 中执行此操作?

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

这是在正确的轨道上吗?我似乎只能找到简单的平面投影的例子。

4

2 回答 2

4

像这样的东西:

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

但是,您的实体应该已经预先配置了必要的外键关系,因此您可以执行以下操作:

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

当然,这会返回每个孩子的所有属性,所以你可能还是想投影孩子:

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()
}
于 2010-01-26T21:50:40.880 回答
0

另一种选择,如果关系的设置不足以使访问器可用:

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()
}
于 2010-01-26T22:10:32.817 回答