Sort children in consultation Linq

Asked

Viewed 393 times

2

I’m having trouble making an ordination in a query where I have to sort the children by the ID, Follow the 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();
}

source compiles without problem but when consulting.

{"Dbsortclause Expressions must have a type that is order comparable. r nName of parameter: key"}

3 answers

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 catch in descending order just do:

orderby c.Id descending

You can also do so:

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

And can also do using lambda expression:

public Grid GetByOrderGridData(long id)
{
     return context.Set<Grid>().Where(x => x.Id.Equals(id)).OrderBy(x => x.Id).FirstOrDefault();
}
  • the ordering has to be by the son of Griddatas, in his solution she is returning the ordering by the father the grid in the case and the alias 'C' in the query.

1

I would summarize it all 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;
}

Once you go to the bank using the FirstOrDefault. you have the data in memory is can it works, one remark here is that the FirstOrDefault returns NULL as Default and if this is not treated your grid.GridDatas.OrderBy will return error.

1


You have two viable options:

  1. Sort the data after consulting

    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;
    
  2. Execute a query separate 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();
    

Browser other questions tagged

You are not signed in. Login or sign up in order to post.