How to do class include in search in Asp.Net MVC

0

Developed a Code First system in Asp.Net MVC In this development I have created a relationship very much and I want to do a search that includes these relationships in a search, below I describe in a better way what I have developed

I have the following classes. Company , Categories and the relationship class CompanyCategories .

Enterprise Class

public class Empresa
{
    public int Id { get; set; }

    public string Nome { get; set; }

    public string Telefone { get; set; }

    public ICollection<EmpresaCategoria> CategoriaEmpresa { get; set; }
}

Class Category

public class Categoria
{
    public int Id { get; set; }

    public string Nome { get; set; }

    public ICollection<EmpresaCategoria> CategoriaEmpresa { get; set; }
}

NxN Relationship Class

public class EmpresaCategoria
{
    [Key]
    public int Id { get; set; }

    [ForeignKey("Categoria")]
    public int CategoriaId { get; set; }

    [ForeignKey("Empresa")]
    public int EmpresaId { get; set; }

    public virtual Categoria Categoria { get; set; }
    public virtual Empresa Empresa { get; set; }
}

In the Controller I have a search that works, but it searches only the Company, I also want to include the Category

    public ActionResult Resultado(string pesquisaEmpresaOuCategoria)
    {
        if (string.IsNullOrEmpty(pesquisaEmpresaOuCategoria))
        {
            return Redirect("Index");
        }

        /*
         *Quero Incluir a categoria nesta pesquisa
         *include
         */

        return View(db.Empresa.Where(x => x.Nome.Contains(pesquisaEmpresaOuCategoria)).ToList());
    }
    
asked by anonymous 24.10.2017 / 14:06

1 answer

1

You can use .Any () for this. .

public ActionResult Resultado(string pesquisaEmpresaOuCategoria)
{
    if (string.IsNullOrEmpty(pesquisaEmpresaOuCategoria))
    {
        return Redirect("Index");
    }

    /*
     *Quero Incluir a categoria nesta pesquisa
     *include
     */

    return View(db.Empresa.Where(x => x.Nome.Contains(pesquisaEmpresaOuCategoria) || x.CategoriaEmpresa.Any(c => c.Categoria.Nome.Contains(pesquisaEmpresaOuCategoria))).ToList());
}

See working in .NET Fiddle.

Another way is also to get the value in the relationship class, like this:

return View(db.EmpresaCategoria.Where(x => x.Empresa.Nome.Contains(pesquisaEmpresaOuCategoria) || x.Categoria.Nome.Contains(pesquisaEmpresaOuCategoria)).ToList());

If you want to return only the companies, you can use .Select() to return only the company.

    
24.10.2017 / 19:25