How to search Join using Entity framework Lambda and Linq
-
As I would do to search in two or more tables.
In the system I'm doing, I have the tables Barco, TypeDeOperacaoDoBarco and ClassBarco
My ta mapping 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 spoof to search
public virtual IEnumerable<TEntity> Buscar(Expression<Func<TEntity, bool>> predicate)
{
return Dbset.Where(predicate);
}
And I use this generic repositorium to make the specific queries of class boats, follow some example 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 TypeDeOperacaoDoBarcoe and ClassBarco, which are different tables, but which are related to boat table, how would I do?
My idea is to show this data in a table
Go down as my bank
-
Good afternoon.
To perform the search according to 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 its class
Tipo
there is a property for relationship betweenTipo
andBarco
, for example:public virtual ICollection<Barco> Barco { get; set; }