How do I sort Lambda by a List property?

Asked

Viewed 263 times

5

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

I’m having trouble with this consultation, specifically in charge ThenBy that tries to sort the sub-list of objects. I know it is in it because when commenting 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 usually use thus, but I don’t know why you’re 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 cannot be Translated into a store Expression.

Example of 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 ordering?

  • 1

    The LINQ to Entities expression translator cannot read "complex" variables like Arrays, so the error.

1 answer

5

Directly from Jon Skeet:

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

So, in my case:

.ThenBy(x => x.Menus.Min(m => m.Ordem))

Browser other questions tagged

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