LINQ投影到表示模型

LINQ投影到表示模型,linq,projection,Linq,Projection,我对LINQ和很多现代数据驱动的应用程序设计技术都很陌生,所以这可能是一个非常基本的问题 我试图创建一个将两个不同实体框架实体投影到一个简单表示模型的投影。假设我有实体父项(属性是ID、Name、Age)和子项(属性是ID、Name、Age,并引用父项)。我想将它们投影到PresentationParent和PresentationChild,其中所有属性都相同,但PresentationParent有一个列表。在林克我该怎么做 from p in entities.Parent select

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

我试图创建一个将两个不同实体框架实体投影到一个简单表示模型的投影。假设我有实体父项(属性是ID、Name、Age)和子项(属性是ID、Name、Age,并引用父项)。我想将它们投影到PresentationParent和PresentationChild,其中所有属性都相同,但PresentationParent有一个列表。在林克我该怎么做

from p in entities.Parent
select new PresentationParent
{
    ID = p.ID,
    Name = p.Name,
    Age = p.Age,
    Children = [[?? What goes here ??]]
}
这条路走对了吗?我似乎只能找到简单、平面投影的例子。

类似这样的例子:

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

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

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

children.ToList()不会创建子对象列表,而不是PresentationChild对象吗?这会编译结果集,但在尝试枚举结果集时失败-它抱怨LINQ to Entities“无法识别”ToList方法,并且“此方法无法转换为存储表达式”不过,如果我使用LINQ to SQL而不是EF,它会起作用。我现在无法亲自尝试,但您可以尝试移动
ToList
方法来包含整个外部查询。这将为L2E提供程序提供更大的灵活性,以便将查询转换为有效的SQL。