Linq订购了父母和子女相关的实体

时间:2014-02-04 16:57:59

标签: c# linq entity-framework linq-to-entities hierarchy

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

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

模型

enter image description here

查询

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

1 个答案:

答案 0 :(得分:1)

怎么样:

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;
    }
}