Pregunta

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

enter image description here

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();
}
¿Fue útil?

Solución

How about:

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;
    }
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top