Linq ordering both parent and child related entities

I have a parent child model where I want to sort by the SortOrder column of both entities. I have the query working but it seems overly verbose and I was wondering if there was a simpler solution to this problem.

I am initially loading the results into an anonymous type (as you can not load complex types directly into the entity framework entities) then querying that type again to load into the entities. I know I could simplify this by implementing a DTO but was interested in a cleaner solution for this use case.

Model

在这里输入图像描述

Query

public List<Group> GetStaticMeasures(int businessUnitID)
{

    var groups = (from g in ctx.Groups.Where(w => w.BusinessUnitID.Equals(businessUnitID)).OrderBy(o => o.SortOrder)
                 select new
                 {
                     ID = g.ID,
                     BusinessUnitID = g.BusinessUnitID,
                     Name = g.Name,
                     SortOrder = g.SortOrder,
                     Datapoints = (from d in ctx.Datapoints where g.ID.Equals(d.StaticGroupID) orderby d.SortOrder select d).ToList()
                 }).ToList();

    var results = from g in groups
                  select new Group
                  {
                      ID = g.ID,
                      BusinessUnitID = g.BusinessUnitID,
                      Name = g.Name,
                      SortOrder = g.SortOrder,
                      Datapoints = g.Datapoints
                  };

    return results.ToList();
}

怎么样:

public IEnumerable<Group> GetStaticMeasures(int businessUnitID)
{
    var groups = ctx.Groups
                   .Include("Datapoints")
                   .Where(w => w.BusinessUnitID.Equals(businessUnitID))
                   .OrderBy(o => o.SortOrder);

    foreach(var g in groups)
    {
       g.Datapoints = g.Datapoints.OrderBy(d => d.SortOrder).ToList();
       yield return g;
    }
}
链接地址: http://www.djcxy.com/p/37654.html

上一篇: Linq集团由父母的财产秩序由孩子

下一篇: Linq订购父母和儿童相关实体