Convert a SQL query into a Linq to SQL instruction
I need to convert the below SQL query into a Linq query
select *
from bancos
where codigobanco in
(select distinct codigobanco开发者_Python百科
from headerarquivo
where (MONTH(datahorageracao)=12) and (YEAR(datahorageracao)=2010))
How could I do to transform this SQL query in a Linq query ?
assuming that datahorageracao is a datetime you didnt post the properties or the domain model but want you want is something like this:
from banco in bancos
let queryauxiliar = (from arquivo in headerarquivo where (arquivo.datahorageracao.Month = 12) && arquivo.datahorageracao.Year = 2010 select arquivo.codigobanco)
where queryauxiliar.Any((val)=>banco.codigobanco == val.codigobanco)
select new Banco()
{
NomeProp = banco.valor
}
Assuming datahorageracao
is of type DateTime.Two different ways you can write LINQ code first using lambda expressions and second using query expression syntax either way works -
//Lambda Expression way get distinct codigobanco...
var codigobancolist =Context.headerarquivo.Where(c=>c.datahorageracao.Month ==12 && c.datahorageracao.Year==2010).Select(c=>c.codigobanco).Distinct();
//Query Expression way to get actual data...
var data= from b in bancos
where b.codigobanco.Contains(codigobancolist)
select b;
var banco = from c in bancos
where headerarquivos
.Select(o => o.codibanco)
.Where(o.MONTH(datahorageracao)=12) and (o.YEAR(datahorageracao)=2010))
.Contains(c.codibanco)
select c;
Pretty sure that should do it.
精彩评论