List group only that contain items

Asked

Viewed 52 times

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 through EF only groups containing Items ?

2 answers

1

First you have to reference the class Item to the 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 an appointment at Grupo to check if you have Item:

var listaGrupos = db.Grupo.Where(a => a.Itens.Count > 0).ToList();
  • Since Items is a Icollection<Item>, I believe you do not have the property Count and the Method Count can have a cost far above the acceptable in this situation. An Option would be the Method Any, however in my view this still a high cost, the best solution in my view would be a Contains, if it is using EF5 or higher.

  • @Tobymosque, as you said and well, either Contains or Any gives. Now at the level of best solution I can no longer have good feedback

1

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

var gruposID = db.Itens.Select(item => item.GrupoId).Distinct().ToList();
var listaGrupos = db.Grupos.Where(grupo => gruposID.Contains(grupo.GrupoId));

Browser other questions tagged

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