How to do a search with Join using Entity framework Lambda and Linq

Asked

Viewed 303 times

0

How do I search two or more tables.

In the system I am doing, I have the tables Barco, Tipodeoperacaodobarco and Classebarco

My mapping is as follows:

       HasRequired(c => c.ClasseBarco)
            .WithMany(c => c.Barcos)
            .HasForeignKey(c => c.ClasseBarcoId);

       HasRequired(c => c.TipoDeOperacaoDoBarco)
            .WithMany(c => c.Barcos)
            .HasForeignKey(c => c.TipoOperacaoId);

I did a generic search

    public virtual IEnumerable<TEntity> Buscar(Expression<Func<TEntity, bool>> predicate)
    {
        return Dbset.Where(predicate);
    }

And I use this generic repository to do the specific searches of the class boats, follow some examples below:

    public IEnumerable<Barco> ObterAtivos()
    {
        return Buscar(c => c.Ativo && !c.Excluido);          
    }

    public Barco ObterPorNome(string nome)
    {
        return Buscar(c => c.Nome == nome).FirstOrDefault();
    }

And if I want to get the Typodeoperacaodobarcoe and the Classebarco, which are different tables but which are related to boat table, as I would?

My idea is to show this data in a table

Follow below as my bank

Dados banco

  • Search from Barco ?

  • @Felippetadeu this, let’s assume that I want to know what the Class and Type of boat of a particular boat

1 answer

0

Good afternoon.

To perform the search as per the comment placed, the search would be as follows:

public Tipo BuscarPorBarco(int idBarco){
    return Buscar(t => t.Barco.IdBarco == idBarco).FirstOrDefault();
}

This answer is given thinking that in your class Tipo there is a property for relationship between Tipo and Barco, being her for example:

public virtual ICollection<Barco> Barco { get; set; }

Browser other questions tagged

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