2010-01-26 71 views
2

我对LINQ以及一般现代数据驱动的应用程序设计技术很感兴趣,所以这可能是一个非常基本的问题。LINQ投影演示模型

我想创建一个投影的几个不同的实体框架实体到一个简单的演示模型。假设我有父项(属性是ID,名称,年龄)和子项(属性是ID,名称,年龄,带有对父项的引用)。我想将它们投影到PresentationParent和PresentationChild,其中所有属性都相同,但PresentationParent有一个List。我如何在LINQ中做到这一点?

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

这是否正确?我似乎只能找到简单的平面投影的例子。

回答

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

这编译,但是当您试图枚举结果集失败 - 它抱怨说,LINQ到实体“不承认” ToList方法,并且“此方法不能转换为商店表达式”。它工作,如果我使用LINQ到SQL而不是EF虽然。 – nlawalker 2010-01-26 22:27:14

+0

我现在无法自己尝试这种方式,但是您可以尝试移动“ToList”方法来代替整个外部查询。这应该使L2E提供者能够更灵活地将查询转换为有效的SQL。 – 2010-01-27 08:37:44

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

不会children.ToList()创建一个Child对象列表,而不是PresentationChild对象? – nlawalker 2010-01-26 22:14:11