Sort the children in query Linq

2

I'm having trouble in ordering a query where I have to sort the children by the ID, Follow Source.

public Grid GetByOrderGridData(long id)
{
    var query = from c in context.Set<Grid>()
                where c.Id == id
                orderby c.GridDatas.OrderBy(p => p.Id)
                select c;
    return query.FirstOrDefault();
}

The source compiles without problem but when querying.

  

{"DbSortClause expressions must have a comparable type. \ r \ nName parameter: key"}

    
asked by anonymous 28.06.2017 / 14:48

3 answers

1

You have two viable options:

  • Order the data after checking

    var query = from c in context.Set<Grid>()
                where c.Id == id
                select c;
    
    
    var retorno = query.FirstOrDefault();
    retorno.GridDatas = retorno.GridDatas.OrderBy(x => x.Id).ToList();
    
    return retorno;
    
  • Run a separate query to bring the child elements:

    var elemento = context.context.Set<Grid>().FirstOrDefault(g => g.Id == id);
    var entry = context.Entry(elemento);
    
    entry.Collection(e => e.GridData).Query().OrderBy(c => c.Id).Load();
    
  • 28.06.2017 / 16:04
    3

    The answer is this:

    public Grid GetByOrderGridData(long id)
    {
            var query = from c in context.Set<Grid>()
                        where c.Id == id
                        orderby c.Id 
                        select c;
            return query.FirstOrDefault();
    }
    

    If you want to order from descending order just do:

    orderby c.Id descending
    

    You can also do this:

    public Grid GetByOrderGridData(long id)
    {
         return = (from c in context.Set<Grid>()
                  where c.Id == id
                  select c).OrderBy(p => p.Id).FirstOrDefault();
    }
    

    And you can also do it using lambda expression:

    public Grid GetByOrderGridData(long id)
    {
         return context.Set<Grid>().Where(x => x.Id.Equals(id)).OrderBy(x => x.Id).FirstOrDefault();
    }
    
        
    28.06.2017 / 15:03
    1

    I would sum it all up in.

    public Grid GetByOrderGridData(long id)
    {
        var grid = (from c in context.Set<Grid>()
                    where c.Id == id
                    orderby c.
                    select c
                  ).FirstOrDefault();
    
        if(grid != null)
            grid = grid.GridDatas.OrderBy(p => p.Id);
    
        return grid;
    }
    

    Since you go to the bank using FirstOrDefault . you have the data in memory it can works, an observation here is that FirstOrDefault returns NULL as Default and if this is not handled its grid.GridDatas.OrderBy will return error.

        
    17.01.2018 / 17:06