LINQ 投影到表示模型
我对 LINQ 和许多现代数据驱动应用程序设计技术非常陌生,所以这可能是一个非常基本的问题。
我正在尝试创建几个不同实体框架实体到简单表示模型的投影。假设我有实体 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 ??]]
}
这到底是在正确的轨道上吗?我似乎只能找到简单、平面投影的例子。
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 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
像这样的事情:
但是,您的实体应该已经预先配置了必要的外键关系,因此您可以执行以下操作:
当然,这将返回每个子项的所有属性,因此您可能想要投影子项反正:
Something like this:
However, your entities should come pre-configured with the necessary foreign key relationships already, so you could do something like this:
Of course, that would return all the properties of each child, so you might want to project the children anyway:
另一种选择,如果关系没有设置得足以让访问器可用:
Another alternative, if the relationship isn't set up enough to have the accessor available: