How to do a Lambda sort with a List property?

5

I believe this has already been asked before. I researched but did not find it.

I'm having trouble with this query, specifically on the ThenBy command that tries to sort the sub-list of objects. I know it's in it because when you comment it, the error does not occur:

var menus = _context.MenuRaiz
    .Include(x => x.Menus)
    .Include(x => x.Menus.Select(m => m.GruposAcesso))
    .Where(x => x.Menus.Any(m => m.GruposAcesso.Any(g => g.Id == permissoes.GrupoAcessoId)))
    .OrderBy(x => x.Ordem)
    .ThenBy(x => x.Menus[0].Ordem) // <-- esse é o culpado! pega ele..
    .ToList();

I often use this way , but I do not know why it's not giving.

Error message :

  

An exception of type 'System.NotSupportedException' occurred in EntityFramework.SqlServer.dll but was not handled in user code

     

Additional information: LINQ to Entities does not recognize the method 'CRM.Domain.Menu get_Item (Int32)' method, and this method can not be translated into a store expression.

Example classes:

MenuRaiz :

public class MenuRaiz 
{
    public MenuRaiz() {
        Menus = new List<Menu>();
    }

    public int Id { get; set; }
    public int Ordem { get; set; }        

    [InverseProperty("MenuRaiz")]
    public virtual List<Menu> Menus { get; set; }
}

Menu :

public class Menu
{
    public int Id { get; set; }
    public int Ordem { get; set; }

    [ForeignKey("MenuRaiz")]
    public int MenuRaizId { get; set; }
    public virtual MenuRaiz MenuRaiz { get; set; }

    [InverseProperty("Menu")]
    public virtual List<GruposAcesso> GruposAcesso { get; set; }
}

What is the correct way to do this sort?

    
asked by anonymous 21.10.2014 / 18:23

1 answer

5

Directly from Jon Skeet :

.OrderBy(e => e.Schedules.Min(s => s.StartDateTime))

So, for my case:

.ThenBy(x => x.Menus.Min(m => m.Ordem))
    
21.10.2014 / 18:35