Linq订购父母和儿童相关实体

我有一个父级子模型,我想按两个实体的SortOrder列进行排序。 我有查询工作,但它似乎过于冗长,我想知道是否有一个更简单的解决方案,以解决这个问题。

我最初将结果加载到匿名类型中(因为无法将复杂类型直接加载到实体框架实体中),然后再次查询该类型以加载到实体中。 我知道我可以通过实施一个DTO来简化这个过程,但是对这个用例更清晰的解决方案感兴趣。

模型

在这里输入图像描述

询问

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/37653.html

上一篇: Linq ordering both parent and child related entities

下一篇: LINQ to entities Child queries where Parent has certain properties