List group only containing items

2

And an example of model :

public class Grupo
{
   public int Id {get;set;}
   public string Nome {get;set;}

   public ICollection<Item> Itens {get;set:}
}

And the items

public class Item
{
  publit int Id {get;set;}
  public int GrupoId {get;set;}
  public string Nome {get;set;}
}

Is there any way I can filter via% w / o of% only groups containing Items?

    
asked by anonymous 25.02.2015 / 02:44

2 answers

1

If you are using EF5 or higher, I believe the best solution involves Contains .

var gruposID = db.Itens.Select(item => item.GrupoId).Distinct().ToList();
var listaGrupos = db.Grupos.Where(grupo => gruposID.Contains(grupo.GrupoId));
    
25.02.2015 / 12:23
1

First of all, you need to reference class Item to Grupo :

public class Item
{
  publit int Id {get;set;}
  public int GrupoId {get;set;}
  public string Nome {get;set;}
  public virtual Grupo Grupo { get; set; } // <-

}

Then just make a query in Grupo to check if it has Item :

var listaGrupos = db.Grupo.Where(a => a.Itens.Count > 0).ToList();
    
25.02.2015 / 11:35