我对LINQ和许多现代数据驱动的应用程序设计技术都很陌生,所以这可能是一个非常基本的问题。
我正在尝试将一些不同的实体框架实体投影到一个简单的表示模型中。假设我有entites Parent(属性是ID,Name,Age)和Child(属性是ID,Name,Age,带有对Parent的引用)。我想将这些项目投影到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 ??]]
}
这是否在正确的轨道上?我似乎只能找到简单平面投影的例子。
答案 0 :(得分: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()
}
答案 1 :(得分: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()
}