将SQL查询转换为Linq to SQL指令

时间:2010-12-08 17:41:51

标签: sql linq

我需要将以下SQL查询转换为Linq查询

select *
from bancos 
where codigobanco in 
   (select distinct codigobanco
   from headerarquivo
   where (MONTH(datahorageracao)=12) and (YEAR(datahorageracao)=2010))

如何在Linq查询中转换此SQL查询?

3 个答案:

答案 0 :(得分:2)

假设datahorageracao是一个日期时间,你没有发布属性或域模型,但想要你想要的是这样的:

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
}

答案 1 :(得分:1)

假设datahorageracao的类型是DateTime。有两种不同的方法可以先使用lambda expressions编写LINQ代码,然后使用query expression语法编写第二种方法 -

//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;

答案 2 :(得分:0)

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;

非常确定应该这样做。