Given the following classes:
MenuRaiz :
public class MenuRaiz
{
public MenuRaiz() {
Menus = new List<Menu>();
}
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int Id { get; set; }
[StringLength(50)]
[Required(AllowEmptyStrings = false)]
public string Descricao { get; set; }
[Required]
public int Ordem { get; set; }
[InverseProperty("MenuRaiz")]
public virtual List<Menu> Menus { get; set; }
}
Menu :
public class Menu
{
public Menu() {
GruposAcessoPermissao = new List<GrupoAcessoPermissao>();
}
[Key, DatabaseGenerated(DatabaseGeneratedOption.None)]
public int Id { get; set; }
[Required, ForeignKey("MenuRaiz")]
public int MenuRaizId { get; set; }
public virtual MenuRaiz MenuRaiz { get; set; }
public int Ordem { get; set; }
[StringLength(250)]
[Required(AllowEmptyStrings = false)]
public string Url { get; set; }
[InverseProperty("Menu")]
public virtual List<GrupoAcessoPermissao> GruposAcessoPermissao { get; set; }
}
Permission Login Group :
public class GrupoAcessoPermissao
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.None)]
public int Id { get; set; }
[Required]
public GrupoAcesso GrupoAcesso { get; set; }
[Required, ForeignKey("Menu")]
public int MenuId { get; set; }
public virtual Menu Menu { get; set; }
}
Generating the following scheme:
Iwanttocreateansqlquerythat,Ibelieve,wouldbethatway,andthatbringstheresultsIhopetoget:
select MR.*, M.* from MenuRaiz MR
left join Menu M on M.MenuRaizId = MR.Id
where M.Id in (
select GAP.MenuId from GrupoAcessoPermissoes GAP
where GAP.GrupoAcesso = @GrupoAcesso
)
order by MR.Ordem, M.Ordem;
What was I trying?
var menusRaiz = _context.MenuRaiz
.Include(x => x.Menus)
.Include(x => x.Menus.Select(m => m.GruposAcessoPermissao))
.Where(x => x.Menus.Any(m => m.GruposAcessoPermissao
.Any(g => g.GrupoAcesso == user.GrupoAcesso)))
.OrderBy(x => x.Ordem)
.ThenBy(x => x.Menus.Min(m => m.Ordem));
And I also tried:
var menusRaiz = _context.MenuRaiz
.Include(x => x.Menus)
.Include(x => x.Menus.Select(m => m.GruposAcessoPermissao))
.Where(x => _context.GrupoAcessoPermissoes
.Where(gap => gap.GrupoAcesso == user.GrupoAcesso)
.Any(gap => x.Menus
.Any(m => m.Id == gap.Id)));
However, they do not work as expected and still very wordy.
How to get a result closer to the sql mentioned, which brings the results as expected?