1

Given a list of groupos, where each groupo has a single empresa and multiple groupos can have the same empresa, how do you get the empresas that contain any of the list's groupos?

I have this Model:

public class Grupo
{
    public int id { get; set; }
    public string descripccion { get; set; }
    [ForeignKey("Empresas")]
    public int empresa { get; set; }

    public virtual empresa Empresas { get; set; }
}


public class empresa
{    
    public int id { get; set; }
    public string descripcion { get; set; }

    public virtual ICollection<Grupo> Grupos { get; set; }
}

So this method gives me a List

private List<Grupo> VerEmpresas(int userId)
{    
    var lista = (from ga in db.GrupoAccesos
    join g in db.Grupos
        on ga.grupo equals g.id
    where ga.usuario == userId
    select g).ToList();
    return lista;
}

and now I want to use this method to show me the empresas that are related to grupo.

Below emp gives a bool, and instead I want all the empresas that are in my list of grupos.

List<Grupo> verEmpresa = VerEmpresas(1);

var emp = (from p in db.Empresas
           select p.Grupos).Contains(verEmpresa);       

ViewBag.empresa = new SelectList(emp, "id", "descripcion");
Risky Martin
  • 2,491
  • 2
  • 15
  • 16
Diego_DX
  • 1,051
  • 1
  • 20
  • 33
  • check this ! http://stackoverflow.com/questions/554649/how-to-bind-linq-data-to-dropdownlist – Gonzalo.- Jul 19 '12 at 22:54
  • My problem is I have a list of grupos and what I want to know is given that list what empresas are relate to that grupos that are in the list – Diego_DX Jul 19 '12 at 22:59

3 Answers3

1

You can try getting the empresa ids from your Grupo list and using the foreign key relationship to get the empresas:

var empresaIds = verEmpresa.Select( v => v.empresa ).Distinct().ToList();
var emp = from p in db.Empresas
          where empresaIds.Contains( p.id )
          select p;
Risky Martin
  • 2,491
  • 2
  • 15
  • 16
0

In your code you are passing 'VerEmpresa' which is a list of Grupo. You should pass one object of Grupo from that list. Try using Any and All method on verEmpresa List. Try something like:

from p in db.Empresas
           where verEmpresa.Any(val => p.Contains(val))
           select p;
Bishnu Paudel
  • 2,083
  • 1
  • 21
  • 39
0

If all you want is the empresas, try:

var emp = (from e in db.Empresas
           from g in db.Grupos
           where e.Grupos.Contains(g)
           select e);
Derek Hunziker
  • 12,996
  • 4
  • 57
  • 105