LINQ投影到演示模型 [英] LINQ projection to presentation model

查看:42
本文介绍了LINQ投影到演示模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

我正在尝试将几个不同的Entity Framework实体投影到一个简单的表示模型.假设我有一个实体Parent(属性是ID,名称,年龄)和Child(属性是ID,名称,年龄,并带有对Parent的引用).我想将它们投影到PresentationParent和PresentationChild,其中所有属性都相同,但是PresentationParent有一个List.我将如何在LINQ中做到这一点?

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.

推荐答案

类似以下内容:

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

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

However, your entities should come pre-configured with the necessary foreign key relationships already, so you could do something like this:

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

当然,这将返回每个孩子的所有属性,因此您可能仍要投影这些孩子:

Of course, that would return all the properties of each child, so you might want to project the children anyway:

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

这篇关于LINQ投影到演示模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆