LINQ / C#-从集合制作DTO?

时间:2018-07-28 04:44:13

标签: c# entity-framework linq

我正在将EF 6.2与SQL一起使用。假设我有这些DTO类:

private class ParentModel
{
    public string FullName { get; set; }
    public IEnumerable<ChildModel> Children { get; set; }
}
private class ChildModel
{
    public string FullName { get; set; }
    public string SpiritAnimalDescription { get; set; }
}

ParentModel源自实体类Parent

ChildModel来自Child,它与另一个实体类SpiritAnimal有关系。请注意,我在.EDMX中将其更改为Children

您可以推断,SpiritAnimal有一个Description字段,我正尝试将其检索到ChildModel字段SpiritAnimalDescription中。

自然地,Parent有一个Child的集合,而集合又有一个SpiritAnimal(根据设计)。现在,我正在尝试使用此代码获取一个List<ParentModel>,该代码目前无法正常工作:

var query = from p in db.Parents
            join c in db.Children on p.Id equals c.Parent_Id
            join sa in db.SpiritAnimals on c.SpiritAnimal_Id equals sa.Id
            select new ParentModel
            {
                FullName = p.LastName + ", " + p.FirstName
                Children = c.Select(a => new ChildModel // <-- Error here :(
                {
                    FullName = a.FirstName + " " + a.LastName,
                    SpiritAnimalDescription = sa.Description
                }
            };

var list = query.ToList();

如何才能尽可能有效地解决此问题?谢谢!

编辑:

为简洁起见,实体类如下所示:

private class Parent
{
    public int Id { get; set; } // PK
    public string LastName { get; set; }
    public string FirstName { get; set; }
}
private class Child
{
    public int Id { get; set; } // PK
    public string LastName { get; set; }
    public string FirstName { get; set; }
    public int Parent_Id { get; set; } // FK
    public int SpiritAnimal_Id { get; set; } // FK
}
private class SpiritAnimal
{
    public int Id { get; set; } // PK
    public string Description { get; set; }
}

2 个答案:

答案 0 :(得分:1)

应该看起来像这样:

var query = from p in db.Parents
        select new ParentModel()
        {
            FullName = p.LastName + ", " + p.FirstName,
            Children = p.Clildren.Select(a => new ChildModel() 
                        {
                            FullName = a.FirstName + " " + a.LastName,
                            SpiritAnimalDescription = sa.Description
                        }).ToList()
        };

答案 1 :(得分:1)

您的代码无法编译和运行,因此无法确定确切的内容。

我只能假设它应该是这样的:

var query = from p in db.Parents
            select new ParentModel
            {
                FullName = p.LastName + ", " + p.FirstName,
                Children = db.Children.Where(c => c.Parent_Id == p.Id)
                    .Select(c => new ChildModel
                    {
                        FullName = c.FirstName + " " + c.LastName,
                        SpiritAnimalDescription = db.SpiritAnimals
                            .FirstOrDefault(sa => sa.Id == c.SpiritAnimal_Id).Description
                    })
            };

注意:使用导航属性。